问题
I am working on a project where I need to capture the browser close event (unload
or 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.
Example
$(window).on('beforeunload', function(e) {
$.ajax({
type: "POST",
url: "url",
data : {'value' : 1},
dataType:'json'
});
return false;
});
回答1:
The beacon API is meant specifically for that. Sending a request as the page is unloading. 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. 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).
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);
};
来源:https://stackoverflow.com/questions/58732391/i-need-to-capture-the-window-onbeforeunload-event