Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 939
mutex Avatar asked Aug 16 '10 03:08

mutex


People also ask

Can I use Onbeforeunload?

This feature is deprecated/obsolete and should not be used.

What triggers Onbeforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

What is Onbeforeunload in JS?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


1 Answers

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.

like image 188
casablanca Avatar answered Oct 03 '22 01:10

casablanca