0

I am currently developing a chat using your typical everyday web programming languages (JavaScript, PHP etc..). The chat is currently fully functional. However, there are several issues that I have yet to solve successfully. One of which being a cross-browser issue.

I am trying to run an AJAX request when a user closes the tab. The PHP for this request looks something like this:

date_default_timezone_set("America/New_York");
    session_start();

    unset($_SESSION["onpage"]);

    if ($_POST['logout'] == "false") {
        sleep(5);
        if (isset($_SESSION["onpage"]) || !empty($_SESSION["onpage"])) die();
    }


    ...
    ...

And the AJAX being:

$.ajax({ // this is jQuery
     type: "POST",
     url: "offline.php",
     data: {
        logout: out ? 'true' : 'false'
     },
     success: function (data) {
         document.location.reload();
     }
});

Basically, when a user closes the tab (in that case $_POST['logout'] will equal false), the request should not finish until the 5 seconds (sleep(5)) have finished. This is because I do not want this request to be fired when a user simply refreshes the page, only when it is confirmed that he left the page.

This is where the cross-browser issue comes in. The functionality I want to achieve works perfectly fine in Safari. This being that on refresh, the request doesn't finish, but if I close the tab, after 5 seconds it does what it is suppose to do and completes. However, on chrome when I hit refresh, refresh itself does not complete until the 5 seconds are over already over which means the request completes regardless. Chrome is waiting for the AJAX to be completed while Safari does not.

Is there any simply fix to this issue?

Edit:

I have tried the following code from a suggestion in the comments:

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

if (isChrome) {
    var formData = new FormData();
    formData.append("logout", "false");

    navigator.sendBeacon("offline.php", formData);
} else {
    $.ajax({ // this is jQuery
        type: "POST",
        url: "offline.php",
        data: {
           logout: 'false'
        },
        success: function (data) {
            document.location.reload();
        }
    });
}

It however did not successfully work.

Shawn31313
  • 5,978
  • 4
  • 38
  • 80

0 Answers0