从 webview 中捕获本机后退按钮事件

Capture the native back button event from within webview

我是 webview 的新手,正在尝试使用它做一个应用程序。我有一个使用 javascript 显示的弹出窗口。它有一个关闭按钮来关闭。除了关闭按钮,我还想使用本机后退按钮。

也就是说,如果用户单击后退按钮,我的弹出窗口应该关闭。

我的疑问是,它是否需要对本机应用程序进行任何更改?或者 webview 将后退按钮操作转换为 webview 可以理解的一些事件,例如按键?

如果您使用的是 Cordova,它会提供一个事件来跟踪 Android 设备上的后退按钮:

document.addEventListener("backbutton", yourCallbackFunction, false);

您可以覆盖此事件并实现您自己的行为。除此之外,应该没有办法跟踪后退按钮事件。

我不知道您是否有 HTML5 支持,但如果有,历史 API 中的 history.pushStatehistory.onpopstate 将完全满足您的要求。

显示弹出窗口时,使用 pushState 通知浏览器有新的历史条目,就好像弹出窗口是一个新页面一样。

然后向 history.onpopstate 添加一个事件侦听器,它会关闭弹出窗口(如果它是打开的)。

您可以尝试混合一些问题及其解决方案:

  1. 拦截 Android

  2. 中的 back button 点击事件
  3. webview 内部(从外部)

  4. will trigger an event在文件

  5. 使用 document.addEventListener 收听此事件并在此处关闭您的 dialog/alert

单击后退按钮将关闭显示模式的 viewcontroller。

我猜你不希望发生这种情况,只需关闭 javascript 模式即可。

是的,您需要更改本机代码。

On native backbutton click, 

if your modal is open:
  close the modal
else:
  do default backbutton action.

下面是详细的解释。

On native backbutton click # your native code to intercept the back button

if your modal is open: 
# there are multiple options here
# first strategy 
#   let javascript inform native side when it opens/closes popup 
#   native just needs to check the status he has
# second strategy
# native asks javascript if he has a modal open
# this is a bit tricky because native can't get a return value from javascript
# native asks javascript to tell native if he has a modal open (native->javascript + javasciprt -> native two function calls)
# native checks what javascript just said

    close the modal
    # this is easy, ask javascript to close it.

我假设您知道如何在 javascript 和本地人之间进行交流,如果不知道,请查看 http://www.smashingmagazine.com/2013/10/best-of-both-worlds-mixing-html5-native-code/

为了进一步帮助 lifeisfoo 所述:

public class WebViewer
WebView webView;
@Override
public void onBackPressed() {
    if (webView.hasPopUp()) {
        webView.loadUrl("javascript:closePopUp()");
    } else {
        super.onBackPressed();
    }
}