在选项卡或浏览器窗口关闭时运行代码,但不在页面重新加载时运行代码

问题描述 投票:0回答:1

我想在用户关闭选项卡或窗口时运行 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,
        });
    }
});
javascript events dom-events page-refresh onbeforeunload
1个回答
0
投票
  • beforeunload 事件通常在刷新时触发 页面以及关闭选项卡或浏览器时。在现代浏览器中, 没有内置的方法来区分页面刷新和页面刷新 选项卡/浏览器在 beforeunload 事件中关闭。

但是,有一个解决方法:

  • 监听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.)
    });
    
© www.soinside.com 2019 - 2024. All rights reserved.