kkakosim
kkakosim

Reputation: 31

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.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");

Upvotes: 0

Views: 5320

Answers (3)

Sameer Zinzuwadia
Sameer Zinzuwadia

Reputation: 3285

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

Thanks

Upvotes: 0

kkakosim
kkakosim

Reputation: 31

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.

Upvotes: 3

balaji
balaji

Reputation: 53

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

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

Upvotes: 0

Related Questions