Rendering HTML in a Webview With Custom Css

Rendering HTML in a WebView with custom CSS

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.

Loading HTML in WebView with custom CSS from non asset folder

The solution to this is the below piece of code:

final File filesDir = getContext().getFilesDir();
final File htmlStuffDir = new File(filesDir, "htmlStuff");
final String baseUrlPath = htmlStuffDir.getAbsolutePath() + "/";

webView.loadDataWithBaseURL("file:///" + baseUrlPath, htmlContent, "text/html", "UTF-8", null);

The / at the end is important and it wouldn't work without that.

Load HTML file to WebView with custom CSS

One possibility (I have not tried this):

WebView.loadDataWithBaseURL(String baseUrl, String data, ..)

takes a baseURL for the document to use to resolve relative URLs. Take a look at the CSS url and construct baseURL so that CSS url will reference local CSS file.

Load CSS file from assets to a WebView with custom HTML and predefined Base URL

If you want to intercept some of the requests from WebView you can do so by overriding shouldInterceptRequest() in WebViewClient like this:

 public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
if (URLUtil.isFileUrl(url) && url.contains(".css")) {
return getCssWebResourceResponseFromAsset();
} else {
return super.shouldInterceptRequest(view, url);
}
}

There is already an excellent detailed answer here https://stackoverflow.com/a/8274881/1112882

HOWEVER
You can not access local file if your base url is not local because of security reasons. So give relative path to your css and then intercept the request.

I would suggest using a pattern to differentiate b/w actual relative and custom relative paths. e.g. use android_asset/my_css_file.css instead of my_css_file.css and modify shouldInterceptRequest() accordingly to always intercept requests starting from android_asset.



Related Topics



Leave a reply



Submit