Android webview活动,如何获取js返回值?

时间:2015-02-12 08:33:50

标签: javascript android

像这样的js代码: function a(){return" hello&#34 ;;}

在android webview活动中,如何调用js函数a()获取返回值" hello" ?

webview.addJavaInterface? webview.loadUrl()?我无法得到它。

请告诉我如何解决问题。

1 个答案:

答案 0 :(得分:0)

我的建议是:

1-定义Javascript界面​​

具有一些方法和属性的普通Java类,使用注释来公开您对webview JS范围所需的方法

public class MyInterface {

private WebView webView;

//pass the reference to the webview in your constructor
public JavascriptCallback(WebView webView) {
    this.webView = webView;
}

//expose this method to the JS scope using annotation
@JavascriptInterface
void sumNumbers(final String num1, final String num2, final String JScallbackFn) {
    this.javascriptCallback(JScallbackFn, num1 + num2);
}

//run the callback into the JS scope
void javascriptCallback(final String callback, final String result) {
    webView.post(new Runnable() {
        @Override
        public void run() { webView.load("javascript:"+callback+"("+result+")", null);
        }
    });
}

2-在webview中注入JavaScript界面​​

webview.addJavascriptInterface(new MyInterface(this.getActivity(), webview), "MyInterface");

3-调用JS方法(在webview中)

MyInterface.sumNumbers(12, 34, showResult);

function showResult(res) {
    document.getElementById('myDiv').innerHTML(res);
}

有关网络视图如何在Android上运行的更详细说明,请查看官方文档http://developer.android.com/guide/webapps/webview.html