3

How do I inject a custom CSS file into a WebView?

I am using Jsoup to extract the HTML Code, then I remove the existing CSS file. I do not know how to inject my local CSS file to the HTML code properly. I am using Stackoverflow as an example. This is some portion of my code. My test.css file is in the assets folder.

Document doc;
        String htmlcode = ""; 
        web = (WebView) findViewById(R.id.webView1);

        try {
            doc = Jsoup.connect("http://stackoverflow.com/users").get();
            doc.head().getElementsByTag("link").remove();
            doc.head().appendElement("link").attr("rel", "stylesheet")
                    .attr("type", "text/css").attr("href", "test.css");
            htmlcode = doc.html();
            web = (WebView) findViewById(R.id.webView1);
            web.loadDataWithBaseURL("file:///android_asset/test.css",
                    htmlcode, "text/html", "UTF-8", null);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

This is what's inside my test.css file, it's the same CSS file being used by Stackoverflow.

Here's a link!

Thank you and I appreciate your time!

Ammar
  • 1,203
  • 5
  • 27
  • 64

1 Answers1

0

Instead of loadDataWithBaseURL try web.loadUrl("file:///android_asset/test.css");

Jason
  • 213
  • 1
  • 3
  • 13