3

我正在使用 Android WebView 并尝试在使用 evaluateJavascript 调用 WebView 后处理从 Java 端的 WebView 返回的 JavaScript 承诺。

文档.java

Button buttonAnnotations = findViewById(R.id.buttonAnnotations);
buttonAnnotations.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        wv.evaluateJavascript("javascript:getAnnotations();", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
            }
        });
    }
});

索引.html

async function getAnnotations() {
    await pdfViewer.getAnnotations().then(result => {
        return JSON.stringify(result ,null,2);
    });
}

如果我将 getAnnotations() 函数更改为不是异步的并返回一个字符串一切正常,所以我试图弄清楚如何在 java 代码中处理这个 promise 以获得结果。

我见过一些类似的问题,但在这种情况下似乎没有一个答案有效。

4

1 回答 1

2

正如我在评论中提到的,您正在从异步函数返回一个 Promise getAnnotations(不能直接在 中使用onReceiveValue)。

为了将结果“推送”getAnnotations回 Android,您必须使用JavascriptInterface

在您的活动中,您可以定义:

@JavascriptInterface
public void onAnnotations(String result) {
    Toast.makeText(WebViewActivity.this, result, Toast.LENGTH_LONG).show();
}

并注册:

webView.addJavascriptInterface(this, "bridge");

在这种情况下,该方法onAnnotations在还包含webView. 因此我使用“this”作为第一个参数。“桥”是命名空间,您可以在其中找到 JavaScript 端的 onAnnotations 函数。

现在您所要做的就是从 JavaScript 调用 Android:

function getAnnotations() {
    pdfViewer.getAnnotations().then(result => {
        bridge.onAnnotations(JSON.stringify(result ,null,2));
    });
}
于 2021-09-27T15:38:18.300 回答