How to detect if user changes tab with JavaScript?

Sometimes, we want to detect if user changes tab with JavaScript.

In this article, we’ll look at how to detect if user changes tab with JavaScript.

How to detect if user changes tab with JavaScript?

To detect if user changes tab with JavaScript, we can listen to the visibilitychange event on document.

For instance, we write:

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

We call document.addEventListener window 'visibilitychange' to listen to the visibilitychange event.

In the event handler, we check if document.visibilityState is 'visible'.

If that’s true, then the tab is active.

Otherwise, it’s not.

Conclusion

To detect if user changes tab with JavaScript, we can listen to the visibilitychange event on document.