栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在CSS中将CSS注入具有webview的网站

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在CSS中将CSS注入具有webview的网站

您不能直接注入CSS,但是可以使用Javascript来操纵页面dom。

public class MainActivity extends ActionBarActivity {  WebView webView;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    webView = new WebView(this);    setContentView(webView);    // Enable Javascript    webView.getSettings().setJavascriptEnabled(true);    // Add a WebViewClient    webView.setWebViewClient(new WebViewClient() {        @Override        public void onPageFinished(WebView view, String url) { // Inject CSS when page is done loading injectCSS(); super.onPageFinished(view, url);        }    });    // Load a webpage    webView.loadUrl("https://www.google.com");}// Inject CSS method: read style.css from assets folder// Append stylesheet to document headprivate void injectCSS() {    try {        InputStream inputStream = getAssets().open("style.css");        byte[] buffer = new byte[inputStream.available()];        inputStream.read(buffer);        inputStream.close();        String enpred = base64.enpreToString(buffer, base64.NO_WRAP);        webView.loadUrl("javascript:(function() {" +     "var parent = document.getElementsByTagName('head').item(0);" +     "var style = document.createElement('style');" +     "style.type = 'text/css';" +     // Tell the browser to base64-depre the string into your script !!!     "style.innerHTML = window.atob('" + enpred + "');" +     "parent.appendChild(style)" +     "})()");    } catch (Exception e) {        e.printStackTrace();    }}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.main, menu);    return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {    // Handle action bar item clicks here. The action bar will    // automatically handle clicks on the Home/Up button, so long    // as you specify a parent activity in AndroidManifest.xml.    int id = item.getItemId();    if (id == R.id.action_settings) {        return true;    }    return super.onOptionsItemSelected(item);  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/432624.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号