Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.beforeunload called twice in Firefox - how to get around this?

I'm creating a popup window that has a beforeunload handler installed. When the "Close" file menu item is used to close the popup, the beforeunload handler is called twice, resulting in two "Are you sure you want to close this window?" messages appearing.

This is a bug with Firefox, and I've reported it here, but I still would like a way to prevent this from happening. Can you think of a sane way of detecting double beforeunload to prevent the double message problem? The problem is that Firefox doesn't tell me which button in the dialog the user elected to click - OK or cancel.

like image 201
Zarkonnen Avatar asked Nov 26 '09 00:11

Zarkonnen


People also ask

What triggers Beforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

What is the difference between Onbeforeunload and Onunload?

One significant difference (other than cancelability) between the onbeforeunload and onunload is that the former is triggered for download links and the latter is not. Example: <a href="https://somewhere.com/thething.zip">download</a> will trigger the onbeforeunload handler, but not the onunload .

What is Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


2 Answers

<script type="text/javascript">
var onBeforeUnloadFired = false;

window.onbeforeunload = function ()
{
    if (!onBeforeUnloadFired) {
        onBeforeUnloadFired = true;
        event.returnValue = "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
   }

   window.setTimeout("ResetOnBeforeUnloadFired()", 10);
}

function ResetOnBeforeUnloadFired() {
   onBeforeUnloadFired = false;
}    
</script>
like image 69
Gayathri Avatar answered Nov 15 '22 01:11

Gayathri


Set a variable in the handler to prevent the dialog coming up the second time. Use setTimeout to reset it afterwards.

like image 27
Mark Bessey Avatar answered Nov 14 '22 23:11

Mark Bessey