Track user activity while taking into account when the user opens in a new tab

498 Views Asked by At

Using JavaScript I want to track the user activity (active or inactive) on my website and I'd like to store this info in my database. I decided to use the activity-detector library which does indeed track the user activity, however if the user has the same webpage opened in 2 tabs then I'm going to end up with inaccurate information so how would I take into account the fact that the user can open the same webpage in 2 tabs?

1

There are 1 best solutions below

0
tom On

With the combination of localStorage and self.window.name you can determine whether other windows/tabs are being used by the same user.

if (!localStorage.getItem('windowName')) { 
    // first visit
    self.window.name = (new Date()).getTime(); 
    localStorage.setItem('windowName', self.window.name);   
} 

if (localStorage.getItem('windowName') && localStorage.getItem('windowName') !== self.window.name) { 
    // i know you, but it's a different window
    console.log('new window'):
    // do stuff, unbind, delete, ... whatever you need to do
    self.window.name = (new Date()).getTime(); 
}