Home > Article > Web Front-end > How to Inject CSS into a Website Displayed in an Android WebView?
Injecting CSS into a Website via WebView in Android
When attempting to alter the appearance of a website loaded within a WebView, such as changing the background color of Google.com to red, by injecting a style.css file from the assets folder, unforeseen errors may arise.
The provided code fails to inject the style.css file because the WebView cannot directly access CSS files.
Solution:
To inject CSS into a website displayed in a WebView, a JavaScript-based approach must be utilized:
<code class="java">public class MainActivity extends ActionBarActivity { // Initialize WebView private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create WebView and enable JavaScript webView = new WebView(this); setContentView(webView); webView.getSettings().setJavaScriptEnabled(true); // Set WebViewClient for page load handling webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { // Inject CSS after page load injectCSS(); super.onPageFinished(view, url); } }); // Load the website webView.loadUrl("https://www.google.com"); } // Inject CSS method private void injectCSS() { try { // Retrieve style.css from assets folder InputStream inputStream = getAssets().open("style.css"); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); // Encode and insert CSS into HTML document head 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';" + "style.innerHTML = window.atob('" + encoded + "');" + "parent.appendChild(style)" + "})()"); } catch (Exception e) { e.printStackTrace(); } } // ... (Other methods and menus) }</code>
This improved code enables the injection of CSS by utilizing JavaScript. It reads the style.css file from the assets folder, encodes it into Base64, and embeds it into the HTML document head, allowing for the manipulation of website styles.
The above is the detailed content of How to Inject CSS into a Website Displayed in an Android WebView?. For more information, please follow other related articles on the PHP Chinese website!