Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pop up a confirmation dialog when the user is closing the window in Safari/Chrome?

In IE and FF, i can attach an event handler to onBeforeUnload, and by passing a string to a property of the event, the user will see a dialog asking him whether he wants to continue with the "unloading" (either closing the window or navigating away).

Safari and Chrome don't support onBeforeUnload, and onUnload seems to be too late. Is there some way to replicate the same functionality in Safari/Chrome?

NOTE: I'm not trying to keep the user hostage. I know this is nagging and un-cool. In fact, my site goes to great lengths to let the user go freely, and have everything in its place when they come back. However, I am hosting other sites inside IFrames, and sometimes these decide to get rid of me and take over the browser, which is what I'm trying to avoid.

Thanks!

like image 946
Daniel Magliola Avatar asked Apr 29 '09 19:04

Daniel Magliola


4 Answers

This works perfectly for me in both Chrome and Safari:

<html><body><p>Test</p>
<script>window.onbeforeunload = function() { return "Sure?"; }</script>
</body></html>

When I try to close the window, I get the prompt.

like image 195
RichieHindle Avatar answered Nov 12 '22 11:11

RichieHindle


StackOverflow itself uses onbeforeunload, and it works fine for me in Safari:

function setConfirmUnload(a){window.onbeforeunload=a?function(){return a}:null}
like image 32
Brian Campbell Avatar answered Nov 12 '22 11:11

Brian Campbell


I checked it in chrome and it seems to be working fine using this:

<body onunload="alert('x');" onbeforeunload="test1();">
like image 2
Ogie Avatar answered Nov 12 '22 10:11

Ogie


This question is covered in slightly more detail in another newer StackOverFlow question: Setting onbeforeunload on body element in Chrome and IE using jQuery

like image 1
AnthonyVO Avatar answered Nov 12 '22 11:11

AnthonyVO