Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a js file from assets into webview after loading html

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

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

But as the html can be any file, I must load the file using some other method. I tried using

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

but it is not loading my js (I call some of its functions, but they didn't worked).

I also tried this solution, but not worked. Basically, I just need to load my js file on the webview so that I can use its functions later. This sounds like a simple task, but I am unable to find any solution for this. Any ideas?

like image 342
berserk Avatar asked Sep 28 '22 22:09

berserk


1 Answers

You will want to use loadDataWithBaseURL for your purpose.

UPDATE:

I don't see an actual method loadScript() that is loaded into the page anywhere so you can try to create the loadScript method yourself before you call to 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')");
like image 96
Max Worg Avatar answered Oct 03 '22 02:10

Max Worg