14

It seems that Google+ checks for notification updates when I activate the tab in Firefox

It'd show "0" every time I activate it, but change to a number of new notifications in a couple of seconds after that.

What's the mechanism allowing to tap into that event? Is there a specific DOM event for that? Or are they using something like onmouseover handler and just consider any kind of activity to be a sufficient indicator of tab activation?

Art
  • 23,747
  • 29
  • 89
  • 101

3 Answers3

9

There is Page visibility document, which describes document.onvisibilitychange event handler.

The usage

document.onvisibilitychange = function() { 
  console.log("Visibility of page has changed!");
};
Fyodor Yemelyanenko
  • 11,264
  • 1
  • 30
  • 38
9

Just a guess because I haven't all relevant browsers available for testing.

What about using the focus event on the window. Whenever a user clicks somewhere this is invoked but also on switching of tabs. To distinguish between a user's actions on the page and a user switching to the page you could check if the event's explicitOriginalTarget points to the window.

window.onfocus=function(event){
    if(event.explicitOriginalTarget===window){
        console.log('switched from tab');
    }
}
Augustus Kling
  • 3,303
  • 1
  • 22
  • 25
  • 2
    `explicitOriginalTarget`is a Mozilla Firefox only property. Doesn't work on major Browsers like Chrome. – Chris Apr 07 '20 at 22:38
5

Unfortunately there's no 100% accurate solution

onvisibilitychange correctly triggers on tab changes, but does not trigger on window changes (ALT+TAB) visibilitychange event is not triggered when switching program/window with ALT+TAB or clicking in taskbar


window.onfocus triggers when the document becomes focused. This works as expected if the tab's focus is already inside the web page, then it correctly triggers when window or tab becomes focused.

But if you have the focus on the URL bar, or in the console, you are already "out of focus", and when you get out of the window or tab and return, you will remain "out of focus", so this event won't trigger until you click inside the page, or navigate into it through TAB key


You can test below how each event triggers (click inside the white iframe to test onfocus/onblur events)

window.onfocus = () => console.log("focus");

window.onblur = () => console.log("out of focus");

document.onvisibilitychange = () => console.log("visibilityState: ", document.visibilityState);
Madacol
  • 3,611
  • 34
  • 33