Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, extract javascript variable from webview using javascript interface

How can I extract this variable bellow from a website to my android code? I guess it should work using javascript interface but how do I get it?

<script type="text/javascript">
    var Ids = "[4161, 104, 121, 202, 1462]";
</script>

And I can't change the code on the website to a method that returns the value.

Any suggestions?

like image 442
just_user Avatar asked Apr 03 '12 10:04

just_user


1 Answers

You can use the javascript: scheme in a webview.loadurl call. It will execute the javascript in the webview page.

From there you can make it call a function in your javascript interface.

webview.loadUrl("javascript:Android.getIds(Ids);");

Android being the name space used to declare your javascript interface.

//Add the javascript interface to your web view
this.addJavascriptInterface(new CustomJavaScriptInterface(webViewContext), "Android");

Beware that javascriptinterface only work with primitive types. So you actually can't pass directly an array. Just use the javascript scheme to loop through your array. I see it is not really an array so you should be fine with just :

public class CustomJavaScriptInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    CustomJavaScriptInterface(Context c) {
        mContext = c;
    }
    

    /** retrieve the ids */
    public void getIds(final String myIds) {
        
        //Do somethings with the Ids
    }
    
}
like image 108
Yahel Avatar answered Oct 31 '22 15:10

Yahel