Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safari does not run callback function on refresh/onbeforeunload on server side (calls client side code)

I am trying to send some requests to the database when the window is unloaded (i.e. when you refresh the page). For some reason, only on Safari, the client side code gets executed, but the request to the server never goes through. When I step through the code manually in the debugger, the server does get the request and processes it fine.

Anyone know why this is happening?

window.onbeforeunload = function() {
  console.log("inside on before unload");
  var requestParam = new a.ListRequest();
  requestParam.setAction('set_delete');
  
  var callback = function(isSuccess, response) {
    if (isSuccess) {
      //do something
    } else {
      // do something else
    }
  };
  
  // Sends request to server
  a.Fetch.list(requestParam, callback);
  
}
like image 713
petranaya Avatar asked Dec 11 '15 20:12

petranaya


2 Answers

Likely the request that happens in the Fetch call is asynchronous and Safari is not waiting for it to finish before moving on to the next page/closing the tab. If you can make the call synchronous it should work. Keep in mind that synchronous calls are generally discouraged and deprecated in some tools.

This answer related to Jquery has a good explanation of synchronous calls: https://stackoverflow.com/a/11755262/1341437

like image 105
craigts Avatar answered Nov 08 '22 15:11

craigts


You can use Beacon API (FF, Chrome, Opera):

window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);
}

User agents will typically ignore asynchronous XMLHttpRequests made in an unload handler. To solve this problem, analytics and diagnostics code will typically make a synchronous XMLHttpRequest in an unload or beforeunload handler to submit the data. The synchronous XMLHttpRequest forces the User Agent to delay unloading the document, and makes the next navigation appear to be slower. There is nothing the next page can do to avoid this perception of poor page load performance.

Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation.

like image 32
Pinal Avatar answered Nov 08 '22 16:11

Pinal