How to detect when a tab is focused or not in Chrome with Javascript? How to detect when a tab is focused or not in Chrome with Javascript? google-chrome google-chrome

How to detect when a tab is focused or not in Chrome with Javascript?


2015 update: The new HTML5 way with visibility API (taken from Blowsie's comment):

document.addEventListener('visibilitychange', function(){    document.title = document.hidden; // change tab text for demo})

The code the original poster gives (in the question) now works, as of 2011:

window.addEventListener('focus', function() {    document.title = 'focused';});window.addEventListener('blur', function() {    document.title = 'not focused';});

edit: As of a few months later in Chrome 14, this will still work, but the user must have interacted with the page by clicking anywhere in the window at least once. Merely scrolling and such is insufficient to make this work. Doing window.focus() does not make this work automatically either. If anyone knows of a workaround, please mention.


The selected answer for the question Is there a way to detect if a browser window is not currently active? should work. It utilizes the Page Visibility API drafted by the W3C on 2011-06-02.


It might work after all, i got curious and wrote this code:

...setInterval ( updateSize, 500 );function updateSize(){  if(window.outerHeight == window.innerHeight){    document.title = 'not focused';               } else {    document.title = 'focused';  }  document.getElementById("arthur").innerHTML = window.outerHeight + " - " + window.innerHeight;}...<div id="arthur">  dent</div>

This code does precisly what you want, but on an ugly way. The thing is, Chrome seems to ignore the title change from time to time (when switching to the tab and holding the mouse down for 1 sec seems to always create this effect).

You will get different values on your screen, yet your title won't change.

conclusion:Whatever you are doing, don't trust the result when testing it!