简体   繁体   中英

Window.onUnload inconsistently sends results to server

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

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.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM