首页 > 解决方案 > Android webview: how to obtain result of evaluateJavascript in a method that invokes evaluateJavascript?

问题描述

As we know in Android, if we want to obtain the result returned by JavaScript code invocation, we can use webview.evaluateJavascript(). For example:

webview.evaluateJavascript("1+2", new ValueCallback<String>() {
     public void onReceiveValue(String value) {
        //value should be 3
     }
});

However, how can I further obtain the result in a method that invokes evaluateJavascript? For example:

public void myFunc() {
   String s;
   webview.evaluateJavascript("1+2", new ValueCallback<String>() {
     public void onReceiveValue(String value) {
        s = value; //This line is only for illustration, it is not syntactically correct
     }
  });
  //Use s to do other things
}

Of course the above snippet doesn't work, but is it possible to achieve similar functionality?

Thanks!

标签: javascriptandroidwebview

解决方案


我这样做:

            String js = "window.openDrawer();";

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                mWebView.evaluateJavascript(js, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {
                        Log.i("MyApp", s);
                    }
                });
            }

我不知道写 '1+2' 是否足够 javascript 来获取返回值。您可能需要在 javascript 中声明该函数,然后让该函数返回 1+2 的结果。

就像是:

String js = "func SumIt(int a, int b) { return (a + b); }; SumIt(1, 2);"

推荐阅读