Android Inject in webview external js, execute function, and raise an alert

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

I want to inject an external javascript in webview and execute one of its functions execute(). After completion an alert is raised and the string returns to the activity
this is how I do it but it doesn't seem to work (the js is already tested)

view.loadUrl("javascript:(function() { var script=document.createElement('script');script.type='text/javascript';script.src=" + jsFileURL + ";" + "document.getElementsByTagName('head').item(0).appendChild(script);window.HTMLOUT.showHTML(execute());})()");

this is how I implement HTMLOUT, while the alert is overrided in ChromeClient

browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT"); browser.setWebViewClient(new mWebViewClient()); browser.setWebChromeClient(new mChromeClient()); browser.loadUrl("file:///android_asset/Travian comx2b.htm");

回答1:

Ok after many many attempts I found a workaround, but unfortunately not the "solution". I used this load view.loadUrl("javascript:" + src + " execute(); " + ""); while the source src comes from a text file script.js which includes my javascript (both functions and plain commands)

//get script InputStream is;         String src= "";         try {             is = getAssets().open("travianbot.js");             int size = is.available();             byte[] buffer = new byte[size];             is.read(buffer);             is.close();             // Convert the buffer into a string.             src = new String(buffer);         } catch (IOException e) {             // TODO Auto-generated catch block             e.printStackTrace();         } 

a sample of the script.js (be careful on line endings ";")

function addItem(v, link, x, y, result) {     //function commands   } function popup() {     alert(execute().split("@")); }      function execute(){       //function commands     additem(...); } // plain commands ....... 

One resolution for a remote script, which I haven't tested it, is to parse the remote script (e.g. as inputstream) and then included it as plain text.



回答2:

please check out this http://lexandera.com/2009/01/adding-alert-support-to-a-webview/

Thanks



回答3:

I think u have to enclose the jsFileUrl in single quotes.

script.src='" + jsFileURL + "';" 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!