1

I need to load some HTML that I construct at runtime into a WebView and apply a CSS file to it placed in the assets directory. And I already have a base URL that I need to provide to the webview's loadDataWithBaseURL function.

Code Snippet (not applying CSS file):

StringBuffer buff = new StringBuffer();
buff.append("<head>");
buff.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/my_css_file.css\"/>");
buff.append("</head>");
buff.append("<div class=\"announcement-header\">");
buff.append("HEADER");
buff.append("</div>");
buff.append("<div class=\"announcement-separator\"></div>");
buff.append("<div class=\"announcement\">");
buff.append("CONTENT");
buff.append("</div>")
WebView.loadDataWithBaseURL(MY_BASE_URL, buff.toString(), "text/html", HTTP.UTF_8, null);

I've looked at these 2 similar issues Issue 1 & Issue 2, but my case is slightly different as I cant give file:///android_asset/ as the base url to the loadDataWithBaseURL function.

Any ideas how I can apply the CSS file in this case ?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

using the code u mentioned and replacing href=\"file:///android_asset/my_css_file.css\" with href=\"my_css_file.css\" did the trick .. thnx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.