Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect tab/window activation in JavaScript

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?

like image 435
Art Avatar asked Aug 06 '11 12:08

Art


People also ask

How to detect tab in js?

Use the visibilitychange event to detect if a browser tab has focus or not, e.g. document. addEventListener('visibilitychange', checkTabFocused) . The event is fired at the document when the contents of its tab have become visible or have been hidden.

How do I know which tab is switching?

You can determine if a tab or window is active by attaching a blur / focus event listener to window. Would also fire for just losing focus on the window, but the window is still visible.


2 Answers

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

The usage

document.onvisibilitychange = function() { 
  console.log("Visibility of page has changed!");
};
like image 78
Fyodor Avatar answered Oct 05 '22 23:10

Fyodor


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');
    }
}
like image 36
Augustus Kling Avatar answered Oct 06 '22 00:10

Augustus Kling