Android WebView doesn't load local css file

10,982

Solution 1

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?

Solution 2

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

Share:
10,982
user3241778
Author by

user3241778

Updated on June 04, 2022

Comments

  • user3241778
    user3241778 almost 2 years

    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