来自资产的 Android WebView JavaScript [英] Android WebView JavaScript from assets

查看:29
本文介绍了来自资产的 Android WebView JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让我的远程 HTML 页面上的 JavaScript 和图像从资产文件夹(或任何本地资源)加载?

How can I make JavaScript and images on my remote HTML page be loaded from assets folder (or just any local resource)?

推荐答案

答案:
1. 您必须将 HTML 加载到字符串中:

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. 使用基本 URL 加载 WebView:


2. Load WebView with base URL:

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

在这种特殊情况下,您应该将所有要在页面上使用的 .js 文件驻留在项目的assets"文件夹下.例如:

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. 在您的远程 html 页面中,您必须加载驻留在您的应用程序中的 .js 和 .css 文件,例如:


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/

WebView 将首先加载您以字符串形式提供的原始 HTML,然后选择 .js、.css 和其他本地资源,然后加载远程内容.

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.

这篇关于来自资产的 Android WebView JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆