Home  >  Article  >  Web Front-end  >  How to Modify the Appearance of a Website Displayed in a WebView?

How to Modify the Appearance of a Website Displayed in a WebView?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 01:58:28959browse

How to Modify the Appearance of a Website Displayed in a WebView?

Injecting CSS into a Website Displayed in a WebView

Problem:

You need to modify the appearance of a website displayed in a WebView (e.g., change the background color of www.google.com to red). Your attempts to inject a style.css file from the assets folder into www.google.com have been unsuccessful.

Solution:

It's not possible to directly inject CSS into a website displayed in a WebView. Instead, you can use JavaScript to manipulate the page's Document Object Model (DOM).

Here's the corrected code for injecting CSS:

<code class="java">public class MainActivity extends ActionBarActivity {

  WebView webView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    webView = new WebView(this);
    setContentView(webView);

    // Enable Javascript
    webView.getSettings().setJavaScriptEnabled(true);

    // Add a WebViewClient
    webView.setWebViewClient(new WebViewClient() {

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

            // Inject CSS when page is done loading
            injectCSS();
            super.onPageFinished(view, url);
        }
    });

    // Load a webpage
    webView.loadUrl("https://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("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';" +
                // Tell the browser to BASE64-decode the string into your script !!!
                "style.innerHTML = window.atob('" + encoded + "');" +
                "parent.appendChild(style)" +
                "})()");
    } catch (Exception e) {
        e.printStackTrace();
    }
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
}</code>

Explanation:

  1. Enable JavaScript on the WebView.
  2. Add a WebViewClient to monitor when the page has finished loading.
  3. Define an injectCSS() method that reads the style.css file from the assets folder, encodes it using Base64, and injects it into the document head using JavaScript.
  4. Call injectCSS() when the page is finished loading.

This approach uses JavaScript to modify the DOM of the website displayed in the WebView, effectively allowing you to inject CSS styles into the page.

The above is the detailed content of How to Modify the Appearance of a Website Displayed in a WebView?. 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