【问题标题】:Android, extract javascript variable from webview using javascript interfaceAndroid,使用javascript接口从webview中提取javascript变量
【发布时间】:2012-04-03 10:35:22
【问题描述】:

如何将下面的变量从网站提取到我的 android 代码中? 我想它应该可以使用 javascript 界面,但我该如何获得它?

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

而且我无法将网站上的代码更改为返回值的方法。

有什么建议吗?

【问题讨论】:

    标签: javascript android


    【解决方案1】:

    您可以在 webview.loadurl 调用中使用javascript: 方案。它将在 webview 页面中执行 javascript。

    从那里你可以让它在你的 javascript 界面中调用一个函数。

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

    Android 是用于声明您的 javascript 接口的名称空间。

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

    请注意,javascriptinterface 仅适用于原始类型。所以你实际上不能直接传递一个数组。只需使用 javascript 方案循环遍历您的数组。我看到它不是一个真正的数组,所以你应该可以:

    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
        }
        
    }
    

    【讨论】:

    • this.addJavaScripInterface(...) 我必须在哪里调用它?
    • 接到电话了。使用 webview :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多