使用 evaluateJavascript 处理来自 Android WebView 的 Promise
Handle Promise from Android WebView with evaluateJavascript
我正在使用 Android WebView 并尝试在调用 Java 端的 WebView 处理 JavaScript promise 的 return使用评估Java脚本。
document.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();
}
});
}
});
index.html
async function getAnnotations() {
await pdfViewer.getAnnotations().then(result => {
return JSON.stringify(result ,null,2);
});
}
如果我将 getAnnotations() 函数更改为不是 async 和 return 字符串都可以正常工作,所以我想弄清楚如何处理java 代码中的此承诺会得到结果。
我见过一些类似的问题,但 none 的答案似乎适用于这种情况。
正如我在评论中提到的,您正在从异步函数 getAnnotations
返回一个 Promise(不能直接在 onReceiveValue
中使用)。
为了将 getAnnotations
的结果“推”回 Android,您必须使用 JavascriptInterface
:
在您的 Activity 中您可以定义:
@JavascriptInterface
public void onAnnotations(String result) {
Toast.makeText(WebViewActivity.this, result, Toast.LENGTH_LONG).show();
}
并注册:
webView.addJavascriptInterface(this, "bridge");
在这种情况下,方法 onAnnotations
在 Activity 中抵抗,其中还包含 webView
。因此,我使用“this”作为第一个论点。
“桥”是命名空间,您可以在其中找到 JavaScript 侧的函数 onAnnotations。
现在您所要做的就是从 JavaScript 拨打 Android:
function getAnnotations() {
pdfViewer.getAnnotations().then(result => {
bridge.onAnnotations(JSON.stringify(result ,null,2));
});
}
我正在使用 Android WebView 并尝试在调用 Java 端的 WebView 处理 JavaScript promise 的 return使用评估Java脚本。
document.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();
}
});
}
});
index.html
async function getAnnotations() {
await pdfViewer.getAnnotations().then(result => {
return JSON.stringify(result ,null,2);
});
}
如果我将 getAnnotations() 函数更改为不是 async 和 return 字符串都可以正常工作,所以我想弄清楚如何处理java 代码中的此承诺会得到结果。
我见过一些类似的问题,但 none 的答案似乎适用于这种情况。
正如我在评论中提到的,您正在从异步函数 getAnnotations
返回一个 Promise(不能直接在 onReceiveValue
中使用)。
为了将 getAnnotations
的结果“推”回 Android,您必须使用 JavascriptInterface
:
在您的 Activity 中您可以定义:
@JavascriptInterface
public void onAnnotations(String result) {
Toast.makeText(WebViewActivity.this, result, Toast.LENGTH_LONG).show();
}
并注册:
webView.addJavascriptInterface(this, "bridge");
在这种情况下,方法 onAnnotations
在 Activity 中抵抗,其中还包含 webView
。因此,我使用“this”作为第一个论点。
“桥”是命名空间,您可以在其中找到 JavaScript 侧的函数 onAnnotations。
现在您所要做的就是从 JavaScript 拨打 Android:
function getAnnotations() {
pdfViewer.getAnnotations().then(result => {
bridge.onAnnotations(JSON.stringify(result ,null,2));
});
}