views:

50

answers:

2

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?

A: 

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.

casablanca
On both Firefox and IE8 I get an error on the call to window.onbeforeunload. Firefox error is "window.onbeforeunload is not a function" and IE comes back with "Object doesn't support this property or method"
mutex
Ok, so the problem is that the plugin attaches an event handler through `addEventListener`/`attachEvent` and not directly through `window.onbeforeunload`. I guess you'll have to modify the plugin code to get a reference to the `beforeunload` function.
casablanca
Thanks! That works now. Any suggestions on avoiding using a global for handler though?
mutex
Not that I can think of. It shouldn't be a problem though, just rename `handler` to something that won't possibly conflict with another name.
casablanca
A: 

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

$('button').click(function(){
    $(window).trigger('beforeunload');
});
Pat
That was pretty much the first thing I tried, but it seems trigger cannot be used on 'beforeunload' as nothing seems to happen when I call it.
mutex
@mutex I was wondering the same thing before I answered so I set up this simple test: http://jsfiddle.net/LpGq9/. Perhaps it has to do with how the form observe plugin is binding the onbeforeunload event handler.
Pat
Yes, you're probably right. The plugin doesn't use bind; it does this instead:if(window.attachEvent){ window.attachEvent('onbeforeunload', beforeunload); }else if(window.addEventListener){ window.addEventListener('beforeunload', beforeunload, true); }
mutex