javascript 是否可以以编程方式触发 onbeforeunload 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3490331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:19:13  来源:igfitidea点击:

Is it possible to trigger the onbeforeunload event programmatically?

javascriptjqueryjquery-pluginsdom-events

提问by mutex

I'm currently using the jquery-form-observeplugin which uses onbeforeunload to prompt the user about "unsaved" changes.

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

But I have a scenario where I need to trigger this on a button click: the button click ultimately leads to the page changing, but I want to prompt the user before they start the process that the button click kicks off...

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

So is there a way to trigger onbeforeunload through jQuery or otherwise?

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

采纳答案by casablanca

I don't know if there is a direct way to do this, but you could always emulate the browser's confirmation box yourself. Here's a simple function I cooked up based on the specs at MSDN:

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

Edit:In jquery.formobserver.js, right after the definition of function beforeunload(e) { ... }, add this line:

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

handler = beforeunload;

Note the change in the original code: window.onbeforeunloadhas been replaced by handler.

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

回答by Pat

You can do it with the .trigger()method:

你可以用.trigger()方法做到这一点:

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