How to apply custom css to android Webview when UR

2019-02-19 20:22发布

问题:

I'm showing my wordpress blog posts on my android app.

Giving wordpress url inside webview

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         mWebView = (WebView) findViewById(R.id.activity_main_webview);
        // Enable Javascript
         WebSettings webSettings = mWebView.getSettings();
         webSettings.setJavaScriptEnabled(true);


        // Force links and redirects to open in the WebView instead of in a browser
        mWebView.setWebViewClient(new WebViewClient());

        mWebView.loadUrl("http://www.myblog.com/start/");        
    }

But I want to remove footer block for that I just want to add

.footer{
diplay:none
}

How can I add this custom css code?

回答1:

When the page is loaded, run some JavaScript, something like:

mWebView.loadUrl("javascript:document.getElementsByClassName('footer')[0].style.display = 'none';");

should do it. On Android 4.4, you can use the WebView.evaluateJavaScript API.

Detecting when the page is loaded such that this JavaScript will work is tricky. The most reliable way to do it would be to install a JavaScript Interface that calls back to Java when the onload event is fired in your HTML. You'd want to have something like this in your Java, before your first call to WebView.loadUrl:

mWebView.addJavascriptInterface(new Object() {

    @JavascriptInterface
    public void onload() {

        // This is executed on a background thread, so post back to UI thread.
        mWebView.post(new Runnable() {

            @Override
            public void run() {
                mWebView.loadUrl("javascript:...");
            }

        });

    }

}, "android");

And then in your HTML:

<body onload="window.android.ready();">

Hope this helps.



回答2:

Another trick is to set custom user agent string for webview

webview.getSettings().setUserAgentString("foo");

and in javascript

if (window.navigator.userAgent == "foo") {
  // do whatever you want :)
}

If you want to preserve default user agent string, you can append "foo" to it and usewindow.navigator.userAgent.includes('foo') in javascript