views:

288

answers:

1

I need to know if the user is currently viewing a tab or not in Google Chrome. I tried to use the events blur and focus binded to the window, but only the blur seems to be working correctly.

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

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

The focus event works weird, only sometimes. If I switch to another tab and back, focus event won't activate. But if I click on the address bar and then back on the page, it will. Or if I switch to another program and then back to Chrome it will activate if the tab is currently focused.

+1  A: 

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!

Bastiaan Linders
The title changes instantly for me. If I change the events to mouseover and mouseout I get instant results.
this is a dead end
Anyway, thanks for the (window.outerHeight == window.innerHeight) part. For this particular project I only need to know if the user is currently focused or not. No need to constantly check, and your code works.
this is a dead end