Loading js file from assets in webview after loading html

I searched a lot, but could not find any solution. I basically make an epub reader in webview with some features like text highlighting etc. For this, I made several javascript files. But to add the js file to the html page, I need to define it inside the html file, for example:

<script src='file:///android_asset/jquery.js'></script> 

But since html can be any file, I have to upload the file using some other method. I tried to use

 view.loadUrl("javascript:loadScript('file:///android_asset/jquery.js','callback')"); 

but it does not load my js (I call some of its functions, but they did not work).

I also tried this solution but did not work. Basically, I just need to upload the js file to webview in order to use its functions later. This seems like a simple task, but I cannot find a solution for this. Any ideas?

+5
source share
1 answer

You want to use loadDataWithBaseURL for your purpose.

UPDATE:

I do not see the actual loadScript () method that loads on the page anywhere, so you can try to create the loadScript method yourself before calling javascript: loadScript ().

  view.loadUrl("javascript:function loadScript(url, callback)" + "{" + " var head = document.getElementsByTagName('head')[0];" + " var script = document.createElement('script');" + " script.type = 'text/javascript';" + " script.src = url;" + " script.onreadystatechange = callback;" + " script.onload = callback;" + " head.appendChild(script);" + "}"); view.loadUrl("javascript:loadScript('file:///android_asset/jquery.js','callback')"); 
+4
source

Source: https://habr.com/ru/post/1211735/


All Articles