DEV Community 👩‍💻👨‍💻

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

Posted on

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 on

Nice one 😄

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.