仅在关闭选项卡或浏览器窗口关闭时运行代码,但不在 javascript beforeunload 事件中刷新时运行代码

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

我正在尝试在 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.