Android WebView JavaScript from assets

杀马特。学长 韩版系。学妹 提交于 2019-11-26 17:26:51
tomurka

Answer:
1. You MUST load the HTML into string:

private String readHtml(String remoteUrl) {
    String out = "";
    BufferedReader in = null;
    try {
        URL url = new URL(remoteUrl);
        in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
            out += str;
        }
    } catch (MalformedURLException e) { 
    } catch (IOException e) { 
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return out;
}


2. Load WebView with base URL:

String html = readHtml("http://mydomain.com/my.html");
mWebView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", "");

In this particular case you should have all .js files you want to use on the page to reside somewhere under "assets" folder of project. For example:

/MyProject/assets/jquery.min.js


3. In your remote html page you have to load .js and .css files that reside in your application like:

<script src="file:///android_asset/jquery.min.js" type="text/javascript"></script>

the same applies to all other local resources like images, etc. their path has to start with

file:///android_asset/

A WebView would first load the raw HTML you have provided as string, then pick .js, .css and other local resourses and then would load remote content.

If dynamically creating your HTML and then using loadDataWithBaseURL make sure any local resources e.g. javascript in your assets folder are referred to in the HTML as file:/// (I Spent hours working this out)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!