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
2009-05-04 17:21:46
Thank you very much...
Software Enthusiastic
2009-05-04 17:32:08
+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
2009-05-04 17:27:41
Unless the browser is Opera, which skips the onunload event if the tab/window/program is being closed.
R. Bemrose
2009-05-04 17:35:29
+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
2009-05-04 18:06:41