[android] Rendering HTML in a WebView with custom CSS

My app is using JSoup to download the HTML of a message board page (let's say in this case it is a page containing the posts of a given thread). I'd like to take this HTML, strip out unwanted items, and apply custom CSS to style it to be 'mobile' in a WebView.

Should I inject the styles into the HTML as I process it (since I will be processing it anyway) or is there a good way to add a CSS file to my app's assets and simply refer to it. I figure the latter would be ideal, but unsure how to go about it.

I see hints in WebView's loadDataWithBaseURL that you can refer to local assets, but not sure how to utilize it.

This question is related to android html css webview

The answer is


You could use WebView.loadDataWithBaseURL

htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + htmlData;
// lets assume we have /assets/style.css file
webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);

And only after that WebView will be able to find and use css-files from the assets directory.

ps And, yes, if you load your html-file form the assets folder, you don't need to specify a base url.


I assume that your style-sheet "style.css" is already located in the assets-folder

  1. load the web-page with jsoup:

    doc = Jsoup.connect("http://....").get();
    
  2. remove links to external style-sheets:

    // remove links to external style-sheets
    doc.head().getElementsByTag("link").remove();
    
  3. set link to local style-sheet:

    // set link to local stylesheet
    // <link rel="stylesheet" type="text/css" href="style.css" />
    doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
    
  4. make string from jsoup-doc/web-page:

    String htmldata = doc.outerHtml();
    
  5. display web-page in webview:

    WebView webview = new WebView(this);
    setContentView(webview);
    webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
    

here is the solution

Put your html and css in your /assets/ folder, then load the html file like so:

    WebView wv = new WebView(this);

    wv.loadUrl("file:///android_asset/yourHtml.html");

then in your html you can reference your css in the usual way

<link rel="stylesheet" type="text/css" href="main.css" />

It's as simple as is:

WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("file:///android_asset/some.html");

And your some.html needs to contain something like:

<link rel="stylesheet" type="text/css" href="style.css" />

If you have your CSS in the internal file storage you can use

//Get a reference to your webview
WebView web = (WebView)findViewById(R.id.webby);

// Prepare some html, it is formated with css loaded from the file style.css
String webContent = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><link rel=\"stylesheet\" href=\"style.css\"></head>"
                      + "<body><div class=\"running\">I am a text rendered with INDIGO</div></body></html>";

//get and format the path pointing to the internal storage
String internalFilePath = "file://" + getFilesDir().getAbsolutePath() + "/";

//load the html with the baseURL, all files relative to the baseURL will be found 
web.loadDataWithBaseURL(internalFilePath, webContent, "text/html", "UTF-8", "");

Is it possible to have all the content rendered in-page, in a given div? You could then reset the css based on the id, and work on from there.

Say you give your div id="ocon"

In your css, have a definition like:

#ocon *{background:none;padding:0;etc,etc,}

and you can set values to clear all css from applying to the content. After that, you can just use

#ocon ul{}

or whatever, further down the stylesheet, to apply new styles to the content.


You can Use Online Css link To set Style over existing content.

For That you have to load data in webview and enable JavaScript Support.

See Below Code:

   WebSettings webSettings=web_desc.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDefaultTextEncodingName("utf-8");
    webSettings.setTextZoom(55);
    StringBuilder sb = new StringBuilder();
    sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
    sb.append(currentHomeContent.getDescription());
    sb.append("</body></HTML>");
    currentWebView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html", "utf-8", null);

Here Use StringBuilder to append String for Style.

sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(currentHomeContent.getDescription());

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to webview

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead? Android Webview gives net::ERR_CACHE_MISS message Swift Open Link in Safari How to load html string in a webview? how to display progress while loading a url to webview in android? Download file inside WebView How to pass html string to webview on android how to get html content from a webview? Android webview slow Android WebView not loading an HTTPS URL