Is there any way of knowing if the user closes a tab in a web browser? Specifically IE7, but also FireFox and others as well. I would like to be able to handle this situatio
Santosh is right, this event will be triggered on many more actions than just clicking the close button of your tab/browser. I've created a little hack to prevent the onbeforeunload action to be triggered by adding the following function on document ready.
$(function () {
window.onbeforeunload = OnBeforeUnload;
$(window).data('beforeunload', window.onbeforeunload);
$('body').delegate('a', 'hover', function (event) {
if (event.type === 'mouseenter' || event.type === "mouseover")
window.onbeforeunload = null;
else
window.onbeforeunload = $(window).data('beforeunload');
});
});
Also, before you trigger any of the events mentioned by Santosh, you need to run this line:
window.onbeforeunload = null;
If you do not want the event to be triggered.
And here's the final code piece:
function OnBeforeUnload(oEvent) {
// return a string to show the warning message (not every browser will use this string in the dialog)
// or run the code you need when the user closes your page
return "Are you sure you want to close this window?";
}