将值从 Javascript *可靠地*返回到 Webview
有一种方法可以从webview中调用javascript函数,然后让它调用Java中的方法来返回结果。就像如何从javascript获取返回值中所述在 android 的 webview 中?
现在,javascript 函数可能会失败(比如由于 javascript 文件中的拼写错误)。在这种情况下,我想用 Java 执行一些故障转移代码。有什么好的方法可以做到这一点?
我当前的代码如下所示:
In Java:
private boolean eventHandled = false;
@Override
public void onEvent() {
eventHandled = false;
webview.loadUrl("javascript:handleEvent()");
// Wait for JS to handle the event.
try {
Thread.sleep(500); // milliseconds
} catch (InterruptedException e) {
// log
}
if (!eventHandled) {
// run failover code here.
}
}
public final MyActivity activity = this;
public class EventManager {
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public void setEventHandled() {
eventHandled = true;
}
};
webview.addJavascriptInterface(new EventManager(), "eventManager");
In javascript:
function handleEvent() {
var success = doSomething();
if (success) {
eventManager.setEventHandled();
}
}
这似乎适合我的情况。有没有比这种“睡一会儿并希望 Javascript 调用到那时完成”方法更好的方法?
There is a way to call javascript function from webview and then let it call a method in Java to return the result. Like described in How to get return value from javascript in webview of android?
Now, the javascript function can fail (say due to a typo in javascript file). In that case, I would like to carry out some failover code in Java. What is a good way to do that?
My current code looks like this:
In Java:
private boolean eventHandled = false;
@Override
public void onEvent() {
eventHandled = false;
webview.loadUrl("javascript:handleEvent()");
// Wait for JS to handle the event.
try {
Thread.sleep(500); // milliseconds
} catch (InterruptedException e) {
// log
}
if (!eventHandled) {
// run failover code here.
}
}
public final MyActivity activity = this;
public class EventManager {
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public void setEventHandled() {
eventHandled = true;
}
};
webview.addJavascriptInterface(new EventManager(), "eventManager");
In javascript:
function handleEvent() {
var success = doSomething();
if (success) {
eventManager.setEventHandled();
}
}
This seems to work fine for my case. Is there a better way than this "sleep for sometime and hope Javascript call is finished by then" method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用同步对象来通知和等待:
You can use a synchronization object for notifying and waiting: