安卓webview活动,如何获取js返回值

Android webview activity,how to get js return value?

本文关键字:获取 js 返回值 何获取 webview 活动 安卓      更新时间:2023-09-26

js代码如下:函数a(){return"hello";}

在androidwebview活动中,如何调用js函数a()得到返回值"hello"?

webview.addJavaInterface?webview.loadUrl()?我拿不到。

请告诉我如何解决这个问题。

我的建议是:

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

有关webview如何在Android上工作的更多详细解释,请查看官方文档http://developer.android.com/guide/webapps/webview.html