user3241778
user3241778

Reputation: 376

Android WebView doesn't load local css file

I am working on an application in Android, where I am using a local html file which includes css files, but It won't work and I have no Idea why. The Java code is like this:

view.loadDataWithBaseURL("file:///android_asset/", content, "text/html", "UTF-8", null);

The HTML code is like this

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">


<title>Starter Template for Bootstrap</title>

<!-- Bootstrap core CSS -->
<link href="../css/main.css" rel="stylesheet">
<style>



</style>

The path is correct, Eclipse WebBrowser shows the html Page correct but if I test it on my Device it's without styles. The Logcat throws the Error "Unknown Chromium Error: -6" Thanks a lot in advance

Upvotes: 4

Views: 12507

Answers (3)

senf78
senf78

Reputation: 1505

On a related note, if you're not storing the file in the assets folder and want to use relative paths, Webview on Android sometimes requires dot-slash before relative paths.

<LINK href="./styles/file.css" type="text/css" rel="stylesheet">

See this post

Upvotes: 1

Wei WANG
Wei WANG

Reputation: 1778

In your case the error -6 means FILE_NOT_FOUND, which probably due to access permission issue on your device.

You may need to put the CSS file under the same folder of your HTML files. For security consideration, webkit engine will apply same-domain policy when accessing local files. i.e. accessing sub-resource files (such as CSS, JS, images) that are not in the same folder of your main HTML file is not allowed.

Upvotes: 0

gaurav5430
gaurav5430

Reputation: 13882

you cannot refer to this path inside a webview. you probably need to store your css file in assets folder and refer to it dynamically:

put CSS in assets folder, do your manipulation with HTML, but refer to CSS by relative path, and load HTML to WebView by loadDataWithBaseURL() method:

webView.loadDataWithBaseURL("file:///android_asset/", htmlString, "text/html", "utf-8", null);
E.g. you have styles.css file, put it to assets folder, create HTML and load it:

StringBuilder sb = new StringBuilder();
sb.append("<HTML><HEAD><LINK href=\"styles.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(tables.toString());
sb.append("</body></HTML>");
webView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html","utf-8", null); 

from: WebView, add local .CSS file to an HTML page?

Upvotes: 4

Related Questions