'visibilitychange fires when page gets reloaded or navigated to other page

  document.addEventListener("visibilitychange", onVisibilityChange, {
    passive: true,
  });

This will fire even when someone navigates away from my page. Ofcourse this is logical. But is there a way to check if someone navigates away?

Edit: What i want is to listen if the user switches to another tab or places the window in the background. this work with visibilityChange but it also fires when the user reloads the page or navigates back and forth in the history. But this is behaviour when i don't want to fire the event



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source