最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Android, extract javascript variable from webview using javascript interface - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Apr 3, 2012 at 10:35 just_userjust_user 12.1k21 gold badges96 silver badges142 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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
    }
    
}
发布评论

评论列表(0)

  1. 暂无评论