我添加了一个额外的代码来处理窗口是否关闭的进一步处理
let disableConfirmation = false;
window.addEventListener('beforeunload', event => {
const confirmationText = 'Are you sure?';
if (!disableConfirmation) {
event.returnValue = confirmationText; // Gecko, Trident, Chrome 34+
return confirmationText; // Gecko, WebKit, Chrome <34
} else {
// Set flag back to false, just in case
// user stops loading page after clicking a link.
disableConfirmation = false;
}
});
如果你想发送任何 ajax 请求并且你已经使用了 jquery,那么在 Confimation 之后
$(window).on('unload', function() {
// async: false will make the AJAX synchronous in case you're using jQuery
axios
.get('ajax_url')
.then(response => {});
});
如果没有使用 jquery,你可以使用 navigator,它需要 navigator 库
navigator.sendBeacon(url, data);
你可以从这里下载这个库:https ://github.com/miguelmota/Navigator.sendBeacon