Is it possible to trigger the onbeforeunload event programmatically?

不打扰是莪最后的温柔 提交于 2019-12-17 19:58:09

问题


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

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?


回答1:


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:

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:

handler = beforeunload;

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




回答2:


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

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


来源:https://stackoverflow.com/questions/3490331/is-it-possible-to-trigger-the-onbeforeunload-event-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!