How to Inject CSS to WebView Android Java

Insert or inject stylesheet css to Android webview java

You can stylize or modify webpages with your own custom CSS style sheet in Android webview. To do that, we need a stylesheet.css and a few lines of code.

In the below code, we will inject a css in the webview of Android after it finishes loading a website, but how do we know if a web page has finished loading already? Yes we can, with the onPageFinished method of Android.

This is the method that gets invoked once the Android webview finishes loading a website so we can do some custom action

@Override
public void onPageFinished(WebView view, String url)


Injecting the CSS into Webview after finish loading

First, put your css file inside the assets folder, rename your css to black or change the css name to your css name in the below code

  webl.setWebViewClient(new WebViewClient() {
            String currentUrl;

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                currentUrl = url;


                if (url.startsWith("http:") || url.startsWith("https:")) {
                    return false;

                } else if (url.startsWith("whatsapp://")) {
                    try {


                        view.getContext().startActivity(
                                new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;

                    } catch (Exception e) {
                        e.getStackTrace();


                    }
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {


                // Inject CSS when page is done loading
                injectCSS();




                                // code here



                super.onPageFinished(view, url);
            }
        });


        // Load a webpage
        webl.loadUrl("http://www.google.com");


    }


    // Inject CSS method: read style.css from assets folder
// Append stylesheet to document head
    private void injectCSS() {
        try {
            InputStream inputStream = getAssets().open("black.css");
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();
            String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
            webl.loadUrl("javascript:(function() {" +
                    "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();



        };

The above code injects the CSS from assets folder (black.css) to webview after it has been loaded. i use this code for setting a night mode in my app. you need define the load url twice, first define it above the shouldOverrideUrlLoading method, then in the onpagefinished method (already defined in the code above)


 

A user requested the Black.css file, so here is it

Download Black.css

, ,

Post navigation

2 thoughts on “How to Inject CSS to WebView Android Java

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.