2

I'd like to track time when user is interacting with the page. As far as I understand user can basically leave a page by

  1. Navigating away (back/forward)
  2. Closing window
  3. Opening new tab and just keeping the old tab in the background
  4. Switch tabs/windows

While I understand I can use "onbeforeunload" for 1 and 2, what can I do about 3 and 4? From my experience it's pretty usual to see people with many tabs open all the time in Chrome/Edge but interacting only with one. Is there any nice trick how to find out that user "deactivated" tab/window?

milanio
  • 4,082
  • 24
  • 34
  • You could set up a `setInterval` that checks whether the window has focus or not – Pytth Mar 30 '17 at 15:14
  • 1
    for number 3 this question could be useful http://stackoverflow.com/questions/20087368/how-to-detect-if-user-it-trying-to-open-a-link-in-a-new-tab – Jpsh Mar 30 '17 at 15:18
  • thanks @user3299379, definitively useful when users navigates away by clicking on a link, but won't help when user just opens a new tab – milanio Mar 30 '17 at 16:33

1 Answers1

2

You could check for the blur event.

  window.addEventListener("blur", function( event ) {
    //DO something   
  }, true);
Pytth
  • 4,008
  • 24
  • 29
  • Thanks! Works like a charm, but with window.addEventListener(...). It doesn't work with document.addEventListener though. Tested on Chrome 56 & Edge. Can you please update the answer and I'll accept it. – milanio Mar 30 '17 at 16:35
  • You got it! Updated the answer :D – Pytth Mar 30 '17 at 20:41