Skip to content
Advertisement

Load HTML in WebView with local css and js

I am displaying a webview with a remote html content get as a string from a remote server. I store the html locally for a no connection use of my application.

Moreover I also store a .js script and a .css style file locally. These files can be updated by the server.

I store all these files at the following paths :

context.getFilesDir()+"content.css"
context.getFilesDir()+"content.js"

In the html string, css and js are referenced like this :

<link rel="stylesheet" href="/content.css" type="text/css" media="screen">                                            
<script src="/content.js"></script>

I load the html using

this.webView.loadDataWithBaseURL(getFilesDir().getAbsolutePath(), html, "text/html", "utf-8", "about:blank");

But the style and the js are not taken into account, so I think something is wrong with the path I use to reference them, or to load the webView. So what is the way to do this ? I found many answers that use the “assets” folder but I do not want to use it since I have to update the css and the js from the server.

Advertisement

Answer

Finally I have found the solution :

  • The css (or js) file is saved in local using this method :

    public static void writeToFile(Context context, String content, String title) throws IOException {
    OutputStreamWriter osw = new OutputStreamWriter(context.openFileOutput(title,Context.MODE_WORLD_READABLE)); osw.write(content); osw.close(); }

  • Then I refer it in the html file using

    <link rel="stylesheet" href="content.css" type="text/css" media="screen">
    <script src="content.js"></script>

  • And finally I have opened the webview using :

    this.webView = (WebView) findViewById(R.id.webview); this.webView.getSettings().setJavaScriptEnabled(true); this.webView.getSettings().setPluginsEnabled(true); this.webView.setHorizontalScrollBarEnabled(false); this.webView.setVerticalScrollBarEnabled(true); this.webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); this.webView.setWebViewClient(this.controller.getWebViewClient()); String basePath = "file://"+getFilesDir().getAbsolutePath()+"/"; this.webView.loadDataWithBaseURL(basePath, data, "text/html", "utf-8", "about:blank");

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement