Android webview load local javascript

2020-05-19 02:40发布

问题:

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.

回答1:

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"/>


回答2:

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.