我想在用户关闭选项卡或窗口时运行 JavaScript 函数,但如果用户只是刷新页面则不运行。
我尝试了
beforeunload
事件的事件处理程序,但它也会在页面重新加载时触发。
有没有办法通过 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.)
});