tags:

views:

1981

answers:

3

How do you prevent javascript page from navigating away?

+1  A: 

Use onunload.

For jQuery, I think this works like so:

$(window).unload(function() { 
  alert("Unloading"); 
  return falseIfYouWantToButBeCareful();
});
altCognito
Thank you very much...
Software Enthusiastic
+2  A: 

In Ayman's example by returning false you prevent the browser window/tab from closing.

window.onunload = function () {
  alert('You are trying to leave.');
  return false;
}
gabor
Thank you very much...
Software Enthusiastic
Unless the browser is Opera, which skips the onunload event if the tab/window/program is being closed.
R. Bemrose
+4  A: 

Using onunload only allows you to display messages, but it will not interrupt the navigation (because it is too late). However, you can use onbeforeunload and it will interrupt navigation:

window.onbeforeunload() {
  return "Are you sure you want to navigate away?";
}

EDIT: Removed confirm() in return statement as this caused a confirm window as expected, but also showed a second confirm with the result of the first confirm.

Jimmie R. Houts