Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onbeforeunload not working in chrome

This is the code which i used for window.onbeforeunload

<head>
<script>

    window.onbeforeunload = func;
    
    function func() 
    {
        var request = new XMLHttpRequest();
        request.open("POST", "exit.php", true); 
        request.onreadystatechange = stateChanged;
        request.send(null);
    }
    function stateChanged()
    {
        if (request.readyState == 4 || request.readyState == "complete")
            alert("Succes!");
    }
    </script>
</head>

this works with IE and Mozilla but does not work with Chrome..... please help...... thanks in advance.....

like image 816
siddhesh Avatar asked Jan 26 '11 06:01

siddhesh


2 Answers

It seems that the only thing you can do with onbeforeunload in recent version of Chrome is to set the warning message.

window.onbeforeunload = function () {
    return "Are you sure";
};

Will work. Other code in the function seems to be ignored by Chrome


UPDATE: As of Chrome V51, the returned string will be ignored and a default message shown instead.

like image 128
LapinLove404 Avatar answered Oct 21 '22 02:10

LapinLove404


Know I'm late to this, but was scratching my head why my custom beforeunload message wasn't working in Chrome and was reading this. So in case anyone else does the same, Chrome from Version 51 onwards no longer supports custom messages on beforeunload. Apparently it's because the feature has been misused by various scams. Instead you get a predefined Chrome message which may or may not suit your purposes. More details at:

https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en#remove-custom-messages-in-onbeforeload-dialogs

Personally do not think the message they've chosen is a great one as it mentions leaving the site and one of the most common legitimate uses for onbeforeunload is for dirty flag processing/checking on a web form so it's not a great wording as a lot of the time the user will still be on your site, just have clicked the cancel or reload button by mistake.

like image 20
Clarkio Avatar answered Oct 21 '22 03:10

Clarkio