You can use the page visibility API to check whether the current tab is active, closed, or minimized. Whenever the user changes the tab, minimizes it, or opens it again, the visibilitychange event gets triggered in the document.

document.addEventListener("visibilitychange", () => {
   if (document.hidden) {
      
      // tab is changed
   } else {
      
      // tab is active
   }
});