简体   繁体   中英

Android webview load local javascript

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM