Android webview load local javascript

2020-05-19 02:43发布

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:

<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.

Thanks if anyone can help.

2条回答
冷血范
2楼-- · 2020-05-19 03:05

You can use 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.

Read the html into a string (htmlStr) and then load it in the webview as mentioned below.

webView.loadDataWithBaseURL("file:///android_asset/", htmlStr, "text/html", "UTF-8", null);

It has worked for me.

查看更多
手持菜刀,她持情操
3楼-- · 2020-05-19 03:16

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:

<script type="text/javascript" src="www/js/jsfile.js"/>
查看更多
登录 后发表回答