Search code examples
google-chromeonbeforeunload

How to fix bug with unbeforeunload in Chrome?


I have the follow code:

window.onbeforeunload = function() {


              $.post(
                   'script/ratings.php', 
                    {
                    data: dataToServer,
                    slider: slider_position_value,
                    article: ARTICLE_NAME
                    },
                      function(data) {

                   });

 };   

that works perfectly in IE and Mozilla. Of oourse, I know about the bug in Chrome due to this event doesn't appear. I need recipe to catch this event and make POST-request into it. Thanks.


Solution

  • The beforeunload event does work in Chrome. However, upon page leave, all requests, including AJAX, are cancelled.

    To get your current code to work, use a synchronous request, by adding async:false to the jQuery.ajax set-up. This blocks the UI till a response is received, and is not recommended.