Window.onUnload inconsistently sends results to server

226 Views Asked by At

I am trying to have the user get an alert when they try to leave the page, and make a post request if they leave, if not, do nothing. Here is my code (using JQuery):

$(window).on("unload", function() { 
    $.post("/delete-room", {
        roomID: roomId
    });
});
$(window).on("beforeunload", function() { 
    return true
})

I (my servers) sometimes get the post request, but only about 1/5 times when I close the tab/unload the page. Is there a reason for this inconsistency? Thanks

1

There are 1 best solutions below

6
Webcoder31 On BEST ANSWER

Unfortunately making ajax call in an unload or onBeforenUnload event handler is not reliable. Most of the calls never reach the backend. Consider using sendBeacon instead.

$(window).on("unload", function() { 
    var formData = new FormData();
    formData.append('roomID', roomId);
    navigator.sendBeacon("/delete-room", formdata);
});

The browser will POST the data without preventing or delaying, whatever is happening (closing tab or window, moving to a new page, etc.).