2

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?

Daniel_Kamel
  • 610
  • 8
  • 29
  • Store the activity times for all tabs and merge them. – jabaa Jun 27 '23 at 12:12
  • Not sure. Maybe setting a [Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) will do the need? Set a unique value to the header. It will be passed along the header while tracking the user activity. – Shri Hari L Jun 27 '23 at 12:17

1 Answers1

4

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(); 
}
tom
  • 9,550
  • 6
  • 30
  • 49