Home > Article > Web Front-end > 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 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!