Javascript to detect if user changes tab

You can determine if a tab or window is active by attaching a blur / focus event listener to window.

in jQuery it would be

$(window).focus(function() {
    //do something
});

$(window).blur(function() {
    //do something
});

quoted from this SO answer: https://stackoverflow.com/a/1760268/680578


In 2022 you can use an event listener with the visibilitychange event:

document.addEventListener("visibilitychange", (event) => {
  if (document.visibilityState == "visible") {
    console.log("tab is active")
  } else {
    console.log("tab is inactive")
  }
});