7

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?

1 Answer 1

13

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
    }
    
}
Sign up to request clarification or add additional context in comments.

2 Comments

this.addJavaScripInterface(...) where I have to call this ?
got called. with webview :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.