如何从webView.evaluateJavascript回调中返回值? [英] How to return value from webView.evaluateJavascript callback?

查看:2628
本文介绍了如何从webView.evaluateJavascript回调中返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个名为 JavascriptBridge 的类,用于在Java和Javascript之间进行通信。

So I have a class named JavascriptBridge that I use to communicate between Java and Javascript.

要将命令发送到javascript,我只需使用这个:

To send commands to javascript, I simply use this:

public void sendDataToJs(String command) {
    webView.loadUrl("javascript:(function() { " + command + "})()");
}

我的问题是我还需要一个函数来返回来自的JavaScript。我尝试使用 webView.evaluateJavascript ,但它会跳过回调,因为evaluateJavascript是在另一个线程上完成的。

My problem is that I would also need a function that return a response from the Javascript. I try using webView.evaluateJavascript, but it skip the callback, as evaluateJavascript is done on another thread.

public String getDataFromJs(String command, WebView webView) {
    String data = null;

    webView.evaluateJavascript("(function() { return " + command + "; })();", new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String s) {
            Log.d("LogName", s); // Print "test"
            // data = s; // The value that I would like to return
        }
    });

    return data; // Return null, not "test"
}

对方法的调用:

String result = getDataFromJs("test", webView); // Should return "test" from the webView

我也尝试过使用 @ JavascriptInterface ,但它给出了相同的结果。

I've also tried using a @JavascriptInterface, but it gives the same result.

推荐答案

没有办法在Android上同步评估Javascript (即在当前线程上)所以你最好的选择是使用 evaluateJavascript 然后等待回调:

There isn't a way to evaluate Javascript synchronously on Android (i.e. on the current thread) so your best bet is to use evaluateJavascript then wait for the callback:

public void getDataFromJs(String command, WebView webView) {
    webView.evaluateJavascript("(function() { return " + command + "; })();", new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String s) {
            returnDataFromJs(s);
        }
    });
}

public returnDataFromJs(String data) {
    // Do something with the result.
}

没有一种方法可以在当前线程上评估Javascript,如Javascript操作可能需要一段时间(JS引擎需要时间来启动),这可以阻止当前线程。

There isn't a method to evaluate Javascript on the current thread, as Javascript operations can take a while (the JS engine needs time to spin up) and this can block the current thread.

这篇关于如何从webView.evaluateJavascript回调中返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆