如何从资产文件夹(或任何本地资源)加载远程 HTML 页面上的 JavaScript 和图像?
来自资产的 Android WebView JavaScript
IT技术
javascript
android
local
assets
                    2021-01-14 08:16:51
                
                    
                
            
        2个回答
            答:
 
1. 您必须将 HTML 加载到字符串中:
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:
String html = readHtml("http://mydomain.com/my.html");
mWebView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", "");
在这种特殊情况下,您应该将要在页面上使用的所有 .js 文件驻留在项目的“资产”文件夹下的某个位置。例如:
/MyProject/assets/jquery.min.js
3. 在您的远程 html 页面中,您必须加载驻留在您的应用程序中的 .js 和 .css 文件,例如: 
<script src="file:///android_asset/jquery.min.js" type="text/javascript"></script>
这同样适用于所有其他本地资源,如图像等。它们的路径必须以
file:///android_asset/
WebView 将首先加载您以字符串形式提供的原始 HTML,然后选择 .js、.css 和其他本地资源,然后加载远程内容。
如果动态创建您的 HTML,然后使用 loadDataWithBaseURL,请确保您的资产文件夹中的任何本地资源(例如 javascript)在 HTML 中被称为 file:/// (我花了几个小时来解决这个问题)
其它你可能感兴趣的问题