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.
The loadUrl() and loadData() methods of Android WebView class are used to load and display web page.
Double-click the “src” folder in your Android project. Double-click the package containing the WebView Activity then double-click the Activity to open it in the editor. Click inside the “onCreate” method to begin typing there.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken web view to show html content.
When a web page is loaded, the browser first reads the HTML text and constructs DOM Tree from it. Then it processes the CSS whether that is inline, embedded, or external CSS and constructs the CSSOM Tree from it. After these trees are constructed, then it constructs the Render-Tree from it.
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
load the web-page with jsoup:
doc = Jsoup.connect("http://....").get();
remove links to external style-sheets:
// remove links to external style-sheets doc.head().getElementsByTag("link").remove();
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");
make string from jsoup-doc/web-page:
String htmldata = doc.outerHtml();
display web-page in webview:
WebView webview = new WebView(this); setContentView(webview); webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With