开发者

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

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.c开发者_JS百科reateElement('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");


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.


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

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


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

Thanks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜