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 😄

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

👋 Kindness is contagious

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

Okay