Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - Is it possible to trigger the onbeforeunload event programmatically?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

' + event.returnValue + '

Press 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...