J. Bauer
J. Bauer

Reputation: 45

trouble with onbeforeunload in conjunction with confirm

I've written some code that's supposed to fire a confirm dialog box when a user leaves the page. If the user provides confirmation, a popup window is supposed to appear; otherwise, it shouldn't. However, the onbeforeunload bit isn't firing—I don't understand why. As it's probably apparent, I'm kind of a JavaScript newbie.

window.onbeforeunload = function () {
    if (confirm("Would you like to take a short survey?")) {
        w = 1000;
        h = 1000;
        var left = (screen.width/2)-(w/2);
        var top = (screen.height/2)-(h/2);
        window.open('http://www.google.com','toolbar=0,resizable = 1, scrollbars = 1, width='+w+',height='+h+', top ='+top+', left='+left);
    }
}

Upvotes: 1

Views: 48

Answers (1)

MazzCris
MazzCris

Reputation: 1830

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.

Source: developer.mozilla.org

The function should return the text to be displayed in the confirm dialog:

window.onbeforeunload = function(e) {
    return 'You are leaving this page.';
};

but it will not necessarily work in all browsers.

Upvotes: 1

Related Questions