【问题标题】:Capture the native back button event from within webview从 webview 中捕获本机后退按钮事件
【发布时间】:2015-08-24 19:35:19
【问题描述】:

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

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

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

【问题讨论】:

  • 你在使用phonegap吗?你到底在用什么?
  • 你能更新你在@goose 的位置吗?

标签: javascript webview android-webview


【解决方案1】:

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

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

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

【讨论】:

  • 你的意思是我应该听上面说的事件并在它触发时执行关闭操作?
  • 是的!编辑详细!
【解决方案2】:

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

  1. 在Android中拦截back button点击事件

  2. Exec a js function 在 web 视图内部(从外部)

  3. 文档中的那个will trigger an event

  4. 使用 document.addEventListener 收听此事件并在此处关闭您的对话框/警报

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

    • 我没有在这个项目中使用 Cordova。
    【解决方案4】:

    单击后退按钮将关闭显示模式的视图控制器。

    我猜你不希望发生这种情况,只需关闭 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/

    【讨论】:

      【解决方案5】:

      为了进一步帮助lifeisfoo 所说的:

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

      【讨论】:

        猜你喜欢
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-31
        • 1970-01-01
        • 2014-04-28
        • 1970-01-01
        • 2010-09-13
        相关资源
        最近更新 更多