javascript Android webview加载本地javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6533207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android webview load local javascript
提问by Rich
I am trying to load a javascript file stored on the device via html file which is loaded via a webview but never seems to load. I have tried using direct url's like you normally would in html and have also tried:
我正在尝试通过 html 文件加载存储在设备上的 javascript 文件,该文件通过 webview 加载但似乎从未加载。我尝试过像通常在 html 中一样使用直接 url,并且还尝试过:
<script type="text/javascript" src="file:///android_asset/www/js/jsfile.js"/>
<script type="text/javascript" src="file:///android_asset/www/js/jsfile.js"/>
JavaScript is enabled on the webview settings too and works fine if I have it on a server.
在 webview 设置中也启用了 JavaScript,如果我在服务器上有它,它就可以正常工作。
Thanks if anyone can help.
谢谢如果有人可以提供帮助。
回答by Paul
Hi actually I thing you should call directly the js file because you are calling it from the browser which considers the asset folder being its root folder. You should use the "file:///" prefix when calling from java code. Try something like this:
嗨,实际上我认为您应该直接调用 js 文件,因为您是从浏览器调用它的,浏览器将资产文件夹视为其根文件夹。从 Java 代码调用时,您应该使用“file:///”前缀。尝试这样的事情:
<script type="text/javascript" src="www/js/jsfile.js"/>
回答by pawan jain
You can use loadDataWithBaseURL
.
您可以使用loadDataWithBaseURL
.
Put all your javascript under an assets
folder and give js file path relative to the assets directory in your script tag (in the html). Don't put a slash in the beginning of src.
将所有 javascript 放在一个assets
文件夹下,并在脚本标记(在 html 中)中提供相对于资产目录的 js 文件路径。不要在 src 的开头放斜线。
Read the html into a string (htmlStr
) and then load it in the webview as mentioned below.
将 html 读入字符串 ( htmlStr
),然后将其加载到 webview 中,如下所述。
webView.loadDataWithBaseURL("file:///android_asset/", htmlStr, "text/html", "UTF-8", null);
It has worked for me.
它对我有用。