是否可以以编程方式触发onb​​eforeunload事件?

mut*_*tex 15 javascript jquery jquery-plugins dom-events

我目前正在使用jquery-form-observe插件,该插件使用onbeforeunload来提示用户"未保存"的更改.

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

那么有没有办法通过jQuery或其他方式触发onb​​eforeunload?

cas*_*nca 3

我不知道是否有直接的方法可以做到这一点,但您始终可以自己模拟浏览器的确认框。这是我根据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
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:在 中jquery.formobserver.js,在 的定义之后function beforeunload(e) { ... },添加以下行:

handler = beforeunload;
Run Code Online (Sandbox Code Playgroud)

注意原始代码的变化:window.onbeforeunload已替换为handler.