将CSS注入WebView而不是onPageFinished

时间:2017-01-28 13:15:57

标签: javascript android css android-webview

这是我将CSS注入Webview的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar().setTitle("Ubqari");
    ww = (WebView) findViewById(R.id.ww);
    ww.getSettings().setJavaScriptEnabled(true);
    ww.getSettings().setDomStorageEnabled(true);
    ww.setWebViewClient(new WebViewClient(){
        public void onPageFinished(WebView view, String url) {
            injectCSS();
        }
    });
    ww.loadUrl("http://ubqari.org");``
}

这里的injectCSS功能:

private void injectCSS() {
    try {
        InputStream inputStream = getAssets().open("style.css");
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        inputStream.close();
        String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
        ww.loadUrl("javascript:(function() {" +
                "alert('Hello! I am an alert box!');"+
                "var parent = document.getElementsByTagName('head').item(0);" +
                "var style = document.createElement('style');" +
                "style.type = 'text/css';" +
                // Tell the browser to BASE64-decode the string into your script !!!
                "style.innerHTML = window.atob('" + encoded + "');" +
                "parent.appendChild(style)" +
                "})()");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我不知道此代码中出了什么问题。我的style.css代码是正确的,但问题出在onPageFinished部分。页面加载完成后,它不会注入CSS。有专家可以回答我吗?

0 个答案:

没有答案