DEV Community

Cover image for How to track browser tab / window switch event
Indrakant Mishra
Indrakant Mishra

Posted on

3

How to track browser tab / window switch event

Hello guys,

In this article we will see how we can track the event of Tab/window change in browser. This method helps in tracking if user switches or navigates from your site to some other site.

We can use an event listener to keep track of event change of tab switch which is visibilitychange. Let's see it in code -

document.addEventListener('visibilitychange', () => {
    console.log('Current State: ', document.visibilityState)
})
Enter fullscreen mode Exit fullscreen mode

Here if user switches to another tab or window we will get hidden in console.log and if user comes back we will see visible in console.log. By default the state will be visible if user is on your website.

*Hope you liked it, please mention in comment for any suggestions or feedback *

Top comments (1)

Collapse
 
shaijut profile image
Shaiju T • Edited

Nice one 😄

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay