Home  >  Article  >  Web Front-end  >  How to Inject Custom CSS into a Website Using WebView in Android?

How to Inject Custom CSS into a Website Using WebView in Android?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 06:21:31110browse

How to Inject Custom CSS into a Website Using WebView in Android?

Inject CSS into a Website Using WebView in Android

Unable to inject CSS directly into a website displayed through a WebView, it's possible to manipulate the page's DOM using JavaScript. Here's how:

1. Enable JavaScript in WebView:

<code class="java">webView.getSettings().setJavaScriptEnabled(true);</code>

2. Add a WebViewClient:

<code class="java">webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        // Inject CSS when page is done loading
        injectCSS();
        super.onPageFinished(view, url);
    }
});</code>

3. Load the Website:

<code class="java">webView.loadUrl("https://www.google.com");</code>

4. Inject CSS using JavaScript:

<code class="java">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);
        webView.loadUrl("javascript:(function() {" +
                "var parent = document.getElementsByTagName('head').item(0);" +
                "var style = document.createElement('style');" +
                "style.type = 'text/css';" +
                // Decode the CSS from BASE64
                "style.innerHTML = window.atob('" + encoded + "');" +
                "parent.appendChild(style)" +
                "})()");
    } catch (Exception e) {
        e.printStackTrace();
    }
}</code>

Note:

  • The style.css file should be in the assets folder of your project.
  • The webView.loadUrl() method must be called after the onPageFinished() callback, as injecting CSS before the page is loaded will have no effect.

The above is the detailed content of How to Inject Custom CSS into a Website Using WebView in Android?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn