Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  199] [ 4]  / answers: 1 / hits: 44488  / 15 Years ago, thu, november 26, 2009, 12:00:00

I have a system where I want to check with the user if they're sure they want to leave the page once a dirty flag is set.



I'm using the following code - In FireFox, I can look at the page source through FireBug and the tag correctly has the onbeforeunload attribute inserted in it.



In Chrome and FireFox, this doesn't happen though and I'm able to navigate away from the page without any warning at all. The jQuery line to update the body tag is definitely being executed, it just isn't performing it.



if ($(body).attr('onbeforeunload') == null) {
if (window.event) {
// IE and Chrome use this
$(body).attr('onbeforeunload', 'CatchLeavePage(event)');
}
else {
// Firefox uses this
$(body).attr('onbeforeunload', 'return false;CatchLeavePage(event)');
}
}


Any ideas how to proceed from here?


More From » jquery

 Answers
36

you cannot abort page unload by returning false. you must return string that will be shown to user in a message box, and he decides if he want to leave or stay on the page (by selecting either 'OK' or 'Cancel' button), so you need to write your code like this:



 window.onbeforeunload = function() {
return Are you sure you want to leave this page bla bla bla?; // you can make this dynamic, ofcourse...
};

[#98215] Tuesday, November 24, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Tue, Feb 12, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;