[英]I need to capture the window.onbeforeunload event
I am working on a project where I need to capture the browser close event ( unload
or beforeunload
).我正在做一个项目,我需要捕获浏览器关闭事件(
unload
或beforeunload
)。 For that I have tried the code below but it's not working.为此,我尝试了下面的代码,但它不起作用。
The code is working only if I open the browser console window (maybe just for a second) but it is required otherwise it's not working.该代码仅在我打开浏览器控制台 window (可能只是一秒钟)时才有效,但它是必需的,否则它不起作用。
$(window).on('beforeunload', function(e) {
$.ajax({
type: "POST",
url: "url",
data : {'value' : 1},
dataType:'json'
});
return false;
});
The beacon API is meant specifically for that.信标 API 专门用于此目的。 Sending a request as the page is unloading.
在页面卸载时发送请求。 https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API
https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API
Beacon requests use the HTTP POST method and requests typically do not require a response.
信标请求使用 HTTP POST 方法,请求通常不需要响应。 Requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example XMLHttpRequest).
请求保证在页面被卸载之前被启动并且它们运行完成,而不需要阻塞请求(例如 XMLHttpRequest)。
window.onunload = function analytics(event) {
if (!navigator.sendBeacon) return;
var url = "https://example.com/analytics";
// Create the data to send
var data = "state=" + event.type + "&location=" + location.href;
// Send the beacon
var status = navigator.sendBeacon(url, data);
// Log the data and result
console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.