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 ?

Community
  • 1
  • 1
MiaN KhaLiD
  • 1,478
  • 1
  • 16
  • 28

1 Answers1

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.

Community
  • 1
  • 1
M-Wajeeh
  • 17,204
  • 10
  • 66
  • 103
  • 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 – MiaN KhaLiD Jul 30 '15 at 11:45