我正在尝试在 beforeunload 事件中运行一些代码。问题是我只希望它在用户关闭选项卡或关闭浏览器窗口时运行,但我不希望它在刷新时运行。如果有其他方法可用,请建议。这是我的代码:
window.addEventListener("beforeunload", (event) => {
event.preventDefault();
// Remove this tab from sessionStorage
sessionStorage.removeItem(tabKey);
// Notify other tabs to close this tab
const activeTabs = JSON.parse(localStorage.getItem(tabKey)) || [];
const updatedTabs = activeTabs.filter((id) => id !== tabId);
if (updatedTabs?.length === 0) {
// All tabs are closed, execute your code
const id = events.getIdentifier();
let URL =
API_URL +
"chat/change-status?url=" +
FIREBASE_FUNCTIONS_URL +
"&id=" +
id +
"&status=" +
Visitor_status.inactive +
"&chat_status=" +
chat_status.no_action;
fetch(URL, {
keepalive: true,
});
}
});
但是,有一个解决方法:
监听visibilitychange 事件。如果页面的可见性 更改为隐藏(在刷新或选项卡/浏览器之前发生) 关闭),设置一个标志。在 beforeunload 事件中,检查标志是否 已经设置好了。如果有,则操作可能是刷新。如果它 还没有,行动可能已经结束了。
let isTabHidden = false;
// Detect when the visibility of the page changes
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
isTabHidden = true;
}
});
window.addEventListener("beforeunload", (event) => {
// Check if the tab's visibility has changed to hidden
if (isTabHidden) {
return;
}
// ... (The rest of your code remains unchanged.)
});