nick
nick

Reputation: 333

Leaving a page confirmation

I have this code which triggers when someone wants to press the back / forward button , close the browser and refresh the page...

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

I don't want this to alert on reloading the same page otherwise it's ok.. And another thing is that which I don't know is how to catch the "Leave" button and "Cancel" button.

Help needed. Thank You..

Upvotes: 1

Views: 86

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

You can't know what page the user is navigating to (nor should you be able to).

You can only know which option the user chose by setting up a timed callback: If you get the callback, the user decided to stay on the page; if not, you know they didn't. Somethign along these lines:

$(window).bind('beforeunload', function(){
  setTimeout(function() {
    // They stayed, maybe
  }, 250);
  return 'Are you sure you want to leave?';
});

But I wouldn't be surprised if there were all kinds of browser compatibility issues doing that. In particular I'd test carefully on target browsers, in particular Firefox. Normally those prompts don't allow JavaScript code to run while they're showing, but...

Upvotes: 2

Related Questions