代码之家  ›  专栏  ›  技术社区  ›  mutex

是否可以通过编程方式触发OnBeforeUnload事件?

  •  10
  • mutex  · 技术社区  · 14 年前

    我目前正在使用 jquery-form-observe 使用onbeforeunload提示用户“未保存”更改的插件。

    但是我有一个场景,我需要在按钮单击时触发它:按钮单击最终导致页面更改,但是我想在用户开始按钮单击启动的过程之前提示他们…

    那么,有没有一种方法可以通过jquery或其他方式触发onbeforeunload?

    2 回复  |  直到 12 年前
        1
  •  3
  •   casablanca    14 年前

    我不知道是否有直接的方法可以做到这一点,但是您可以自己模拟浏览器的确认框。下面是我根据 specs at MSDN :

    function triggerBeforeUnload() {
      var event = {};
      handler(event);
    
      if (typeof event.returnValue == 'undefined' ||
          confirm('Are you sure you want to navigate away from this page?\n\n' + event.returnValue + '\n\nPress OK to continue, or Cancel to stay on the current page.')) {
        // Continue with page unload
      } else {
        // Cancel page unload
      }
    }
    

    编辑: jquery.formobserver.js ,在定义 function beforeunload(e) { ... } ,添加此行:

    handler = beforeunload;
    

    注意原始代码的更改: window.onbeforeunload 已被替换为 handler .

        2
  •  2
  •   Pat    14 年前

    你可以用 .trigger() 方法:

    $('button').click(function(){
        $(window).trigger('beforeunload');
    });