[英]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):
这是我的代码(使用 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.我(我的服务器)有时会收到发布请求,但在我关闭选项卡/卸载页面时只有大约 1/5 次。 Is there a reason for this inconsistency?
这种不一致是否有原因? Thanks
谢谢
Unfortunately making ajax call in an unload
or onBeforenUnload
event handler is not reliable.不幸的是,在
unload
或onBeforenUnload
事件处理程序中调用 ajax 并不可靠。 Most of the calls never reach the backend.大多数调用永远不会到达后端。 Consider using sendBeacon instead.
考虑改用sendBeacon 。
$(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.).无论发生什么(关闭选项卡或
POST
、移动到新页面等),浏览器都会在不阻止或延迟的情况下发布数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.