繁体   English   中英

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

[英]Android webview activity,how to get js return value?

像这样的js代码:function a(){return“ hello”;}

在android webview活动中,如何调用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-在您的Web视图中注入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);
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM