This is a very common issue. So far it doesn't seem there is a perfect solution. This is the best I can do though:
Code
$(function () {
$("a").click(function (evt) {
confirm_leave = false;
});
});
var confirm_leave = true;
window.onbeforeunload = function (evt) {
if (confirm_leave === true) {
var leave_message = "Are you sure you want to leave this page?";
if (!evt) evt = window.event;
evt.cancelBubble = true;
evt.returnValue = leave_message;
if (evt.stopPropagation) {
evt.stopPropagation();
evt.preventDefault();
}
return leave_message;
} else {
confirm_leave = true;
}
};
Explanation
First, if there are any links (can include buttons too) then this assigns a click event that sets a flag to disable the confirmation message.
$(function () {
$("a").click(function (evt) {
confirm_leave = false;
});
});
Next, the default value of the flag is set to true (enable the confirmation message).
var confirm_leave = true;
Then the onbeforeunload event handler is set. The function checks the flag to see if the confirmation message should be shown.
Flag Is True
1. store the confirmation message to display.
2. get the appropriate event.
3. don't allow event bubbling/propagation.
4. set the event's returnValue to the confirmation message. (Browsers including IE)
5. return the confirmation message (Other browsers).
if (confirm_leave === true) {
var leave_message = "Are you sure you want to leave this page?";
if (!evt) evt = window.event;
evt.cancelBubble = true;
evt.returnValue = leave_message;
if (evt.stopPropagation) {
evt.stopPropagation();
evt.preventDefault();
}
return leave_message;
}
Flag Is False
If the flag is not set to true, then set it to true. Since the flag has a default to true, then this flag must have been changed due to a link/button click.
else {
confirm_leave = true;
}
Problem
There is a potential problem with this solution though. If the user opens the link in a new window, the flag will be set to false but the onbeforeunload event handler will not be called (causing the flag to not be reset). Hopefully this will get things going for you though.