views:

286

answers:

3

When a user leaves one page of my website, there should be a warning message which gives the user the option to stay on the page:

"Are you sure that you want to close this page?"

It doesn't matter if the next page is an internal or external page.

I thought this could be done with the onUnload event handler, couldn't it?

<body onunload="confirmClose()">

The confirmClose() function must then show a message box with two buttons so that the user can choose between "Really leave" or "Stay".

function confirmClose() {
    return confirm('Really leave this page?')
}

But this function can't stop the unload, right?

Do you have a solution for my problem? Thanks in advance!

+1  A: 

The browser takes care of displaying the confirm window. You need to return the string with the message that you want to ask. Also, you may want to use onbeforeunload for cross browser compatibility.

Pekka
+4  A: 

You can add an onbeforeunload event. Note that it can only return a text string to include in the dialog the browser will display when the event is called. You can't tweak the dialog beyond that, nor can you trigger your own confirm as you're trying to do.

I'd note that this is very, very annoying behaviour except in a few specific situations. Unless you're saving me from significant data loss with this, please don't do it.

ceejayoz
Thank you very much! All answers were good and helpful - but I have to choose one as the best. ;) So I choose your one.
+2  A: 

You can only provide the text. The browser handles the dialog box (security reasons). Here is some code you can use:

window.onbeforeunload = function (e) {
    var e = e || window.event;
    var msg = 'Are you sure you want to leave?';

    // For IE and Firefox
    if (e) {
        e.returnValue = msg;
    }

    // For Safari / chrome
    return msg;
}

Try this out on different browsers, though. You'll notice the message should be constructed differently depending on the different browsers' dialog wording.

Here is what I use:

if (IsChrome) {
    return 'You were in the middle of editing. You will lose your changes if you leave this page';
} else {
    return 'You were in the middle of editing. Press OK to leave this page (you will lose your changes).';
}
Gabriel McAdams