Santos is right, this event will fire in many other actions than just clicking the close button on your tab / browser. I created a small hack to prevent onbeforeunload from triggering by adding the following function to the finished document.
$(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'); }); });
In addition, before starting any of the events mentioned by Santos, you need to run this line:
window.onbeforeunload = null;
If you do not want the event to be fired.
And here is the final piece of code:
function OnBeforeUnload(oEvent) {
source share