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)

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 *

Source link