window.onbeforeunload ajax request in Chrome

JavascriptAjaxGoogle Chrome

Javascript Problem Overview


I have a web page that handles remote control of a machine through Ajax. When user navigate away from the page, I'd like to automatically disconnect from the machine. So here is the code:

window.onbeforeunload = function () {
  bas_disconnect_only();
}

The disconnection function simply send a HTTP GET request to a PHP server side script, which does the actual work of disconnecting:

function bas_disconnect_only () {
   var xhr = bas_send_request("req=10", function () {
   });
}

This works fine in FireFox. But with Chrome, the ajax request is not sent at all. There is a unacceptable workaround: adding alert to the callback function:

function bas_disconnect_only () {
   var xhr = bas_send_request("req=10", function () {
     alert("You're been automatically disconnected.");
   });
}

After adding the alert call, the request would be sent successfully. But as you can see, it's not really a work around at all.

Could somebody tell me if this is achievable with Chrome? What I'm doing looks completely legit to me.

Thanks,

Javascript Solutions


Solution 1 - Javascript

This is relevant for newer versions of Chrome.

Like @Garry English said, sending an async request during page onunload will not work, as the browser will kill the thread before sending the request. Sending a sync request should work though.

This was right until version 29 of Chrome, but on Chrome V 30 it suddenly stopped working as stated here.

It appears that the only way of doing this today is by using the onbeforeunload event as suggested here.

BUT NOTE: other browsers will not let you send Ajax requests in the onbeforeunload event at all. so what you will have to do is perform the action in both unload and beforeunload, and check whether it had already taken place.

Something like this:

var _wasPageCleanedUp = false;
function pageCleanup()
{
    if (!_wasPageCleanedUp)
    {
        $.ajax({
            type: 'GET',
            async: false,
            url: 'SomeUrl.com/PageCleanup?id=123',
            success: function ()
            {
                _wasPageCleanedUp = true;
            }
        });
    }
}
 

$(window).on('beforeunload', function ()
{
    //this will work only for Chrome
    pageCleanup();
});

$(window).on("unload", function ()
{
    //this will work for other browsers
    pageCleanup();
});

Solution 2 - Javascript

I was having the same problem, where Chrome was not sending the AJAX request to the server in the window.unload event.

I was only able to get it to work if the request was synchronous. I was able to do this with Jquery and setting the async property to false:

$(window).unload(function () {
   $.ajax({
     type: 'GET',
     async: false,
     url: 'SomeUrl.com?id=123'
   });
});

The above code is working for me in IE9, Chrome 19.0.1084.52 m, and Firefox 12.

Solution 3 - Javascript

Checkout the Navigator.sendBeacon() method that has been built for this purpose.

The MDN page says:

> The navigator.sendBeacon() method can be used to asynchronously > transfer small HTTP data from the User Agent to a web server.


This method addresses the needs of analytics and diagnostics code that > typically attempt to send data to a web server prior to the unloading > of the document. Sending the data any sooner may result in a missed > opportunity to gather data. However, ensuring that the data has been > sent during the unloading of a document is something that has > traditionally been difficult for developers.

This is a relatively newer API and doesn't seems to be supported by IE yet.

Solution 4 - Javascript

Synchronous XMLHttpRequest has been deprecated (Synchronous and asynchronous requests). Therefore, jQuery.ajax()'s async: false option has also been deprecated.

It seems impossible (or very difficult) to use synchronous requests during beforeunload or unload (https://stackoverflow.com/questions/55676319/ajax-synchronous-request-failing-in-chrome?source=post_page---------------------------). So it is recommended to use sendBeacon and I definitely agree!

Simply:

window.addEventListener('beforeunload', function (event) {  // or 'unload'
    navigator.sendBeacon(URL, JSON.stringify({...}));

    // more safely (optional...?)
    var until = new Date().getTime() + 1000;
    while (new Date().getTime() < until);
});

Solution 5 - Javascript

Try creating a variable (Boolean preferably) and making it change once you get a response from the Ajax call. And put the bas_disconnect_only() function inside a while loop. I also had a problem like this once. I think this happens because Chrome doesn't wait for the Ajax call. I don't know how I fixed it and I haven't tried this code out so I don't know if it works. Here is an example of this:

var has_disconnected = false;
window.onbeforeunload = function () {
    while (!has_disconnected) {
        bas_disconnect_only();
        // This doesn't have to be here but it doesn't hurt to add it:
        return true;
    }
}

And inside the bas_send_request() function (xmlhttp is the HTTP request):

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        has_disconnected = true;
}

Good luck and I hope this helps.

Solution 6 - Javascript

I had to track any cases when user leave page and send ajax request to backend.

var onLeavePage = function() {
    $.ajax({
        type: 'GET',
        async: false,
        data: {val1: 11, val2: 22},
        url: backend_url
    });
};

/**
 * Track user action: click url on page; close browser tab; click back/forward buttons in browser
 */
var is_mobile_or_tablet_device = some_function_to_detect();
var event_name_leave_page = (is_mobile_or_tablet_device) ? 'pagehide' : 'beforeunload';
window.addEventListener(event_name_leave_page, onLeavePage);

/**
 * Track user action when browser tab leave focus: click url on page with target="_blank"; user open new tab in browser; blur browser window etc.
 */
(/*@cc_on!@*/false) ?  // check for Internet Explorer
    document.onfocusout = onLeavePage :
    window.onblur = onLeavePage;

Be aware that event "pagehide" fire in desktop browser, but it doesn't fire when user click back/forward buttons in browser (test in latest current version of Mozilla Firefox).

Solution 7 - Javascript

Try navigator.sendBeacon(...);

try {
        // For Chrome, FF and Edge
        navigator.sendBeacon(url, JSON.stringify(data));
    }
    catch (error)
    {
        console.log(error);
    }

    //For IE
    var ua = window.navigator.userAgent;
    var isIEBrowser = /MSIE|Trident/.test(ua);

    if (isIEBrowser) {
        $.ajax({
            url: url,
            type: 'Post',
            .
            .
            .
        });
    }

Solution 8 - Javascript

I've been searching for a way in which leaving the page is detected with AJAX request. It worked like every time I use it, and check it with MySQL. This is the code (worked in Google Chrome):

    $(window).on("beforeunload", function () {
        $.ajax({
             type: 'POST',
             url: 'Cierre_unload.php',
             success: function () {
             }
        })
    })

Solution 9 - Javascript

I felt like there wasn't an answer yet that summarized all the important information, so I'm gonna give it a shot:

Using asynchronous AJAX requests is not an option because there is no guarantee that it will be sent successfully to the server. Browsers will typically ignore asynchronous requests to the server. It may, or may not, be sent. (Source)

As @ghchoi has pointed out, synchronous XMLHTTPRequests during page dismissal have been disallowed by Chrome (Deprecations and removals in Chrome 80). Chrome suggests using sendBeacon() instead.

According to Mozilla's documentation though, it is not reliable to use sendBeacon for unload or beforeunload events.

> In the past, many websites have used the unload or beforeunload events to send analytics at the end of a session. However, this is extremely unreliable. In many situations, especially on mobile, the browser will not fire the unload, beforeunload, or pagehide events.

Check the documentation for further details: Avoid unload and beforeunload

Conclusion: Although Mozilla advises against using sendBeacon for this use case, I still consider this to be the best option currently available.

When I used sendBeacon for my requirements, I was struggling to access the data sent at the server side (PHP). I could solve this issue using FormData as recommended in this answer.

For the sake of completeness, here's my solution to the question:

window.addEventListener('beforeunload', function () {
    bas_disconnect_only();
});

function bas_disconnect_only () {
    const formData = new FormData();
    formData.append(name, value);
    navigator.sendBeacon('URL', formData);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionlang2View Question on Stackoverflow
Solution 1 - JavascriptMohochView Answer on Stackoverflow
Solution 2 - JavascriptGarry EnglishView Answer on Stackoverflow
Solution 3 - JavascriptSparkyView Answer on Stackoverflow
Solution 4 - JavascriptghchoiView Answer on Stackoverflow
Solution 5 - JavascriptMetod MedjaView Answer on Stackoverflow
Solution 6 - JavascriptsNICkerssssView Answer on Stackoverflow
Solution 7 - JavascriptAmit SharmaView Answer on Stackoverflow
Solution 8 - JavascriptXabier Aparicio MuñoaView Answer on Stackoverflow
Solution 9 - JavascriptJanView Answer on Stackoverflow