79

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.

fent
  • 17,861
  • 15
  • 87
  • 91
  • Did you try to attach those events to `docment` instead of `window`? – Crozin Apr 27 '10 at 11:42
  • I'm not sure whether it affects event detection, but the `window.focus` action is disabled (or at least buggy) in Chrome. See [here](http://code.google.com/p/chromium/issues/detail?id=1674) and [here](http://stackoverflow.com/questions/2703314/in-google-chrome-how-do-i-bring-an-existing-popup-window-to-the-front-using-java) for more. – brahn Apr 27 '10 at 11:51
  • Doesn't work with document either and this is for the focus event, not the focus action. I think I'll change my approach to this and change the event to either mouseover or window scrolling. For this scenario it's appropriate. – fent Apr 27 '10 at 12:04
  • The code you in the question works perfectly in Chrome as of 2011. The solution does not work. – ninjagecko May 31 '11 at 07:26
  • possible duplicate of [Is there a way to detect if a browser window is not currently active?](http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active) – Kijewski Jul 15 '12 at 15:16

7 Answers7

141

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.

ninjagecko
  • 88,546
  • 24
  • 137
  • 145
  • 1
    The way to get this to work without the user having to click somewhere first is to add "window.focus()" to the window.onload event. The side effect of this is that if the window is the target of a link and was already open behind the current window, it's going to be brought to the front. Note that this solution only detects loss of focus, not that it was caused by switching tabs. For example, if loss of focus was due to the user clicking inside an iframe, you have to eliminate that: – SPitBalls.com Feb 04 '12 at 21:25
  • function iframeMouse(over) { oif = over; } window.addEventListener('blur', function() { document.title = oif ? "iframe focused" : "not focused"; }); – SPitBalls.com Feb 04 '12 at 21:33
  • 5
    For a more in-depth robust answer see this. http://forums.greensock.com/topic/9059-cross-browser-to-detect-tab-or-window-is-active-so-animations-stay-in-sync-using-html5-visibility-api/ – Blowsie May 08 '14 at 10:21
  • 3
    Use `document.visibilityState` to get current visibility state – Oleg Feb 27 '18 at 14:12
8

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.

Community
  • 1
  • 1
thirdender
  • 3,891
  • 2
  • 30
  • 33
2

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
  • 1,861
  • 2
  • 13
  • 15
  • The title changes instantly for me. If I change the events to mouseover and mouseout I get instant results. – fent Apr 27 '10 at 16:44
  • 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. – fent Apr 27 '10 at 17:26
2

For anyone who wants to swap page titles on blur and then go back to the original page title on focus:

// Swapping page titles on blur
var originalPageTitle = document.title;

window.addEventListener('blur', function(){
    document.title = 'Don\'t forget to read this...';
});

window.addEventListener('focus', function(){
    document.title = originalPageTitle;
});
stacigh
  • 676
  • 1
  • 7
  • 13
0

This could work with JQuery

$(function() {
    $(window).focus(function() {
        console.log('Focus');
    });

    $(window).blur(function() {
        console.log('Blur');
    });
});
kongaraju
  • 9,344
  • 11
  • 55
  • 78
  • I think this will not help because as he reported browser does NOT fire event function you have attached in 'blur'. So as in your example and code `console.log('Blur');` will NOT be called in some situations. – psulek Feb 07 '13 at 20:08
0

I found that adding onblur= and onfocus= events to inline bypassed the issue:

Trass Vasston
  • 679
  • 2
  • 6
  • 19
-2

In chrome you can run a background script with a timeout of less than 1 second, and when the tab does not have focus chrome will only run it every second. Example;

This doesn't work in Firefox or Opera. Don't know about other browsers, but I doubt it works there too.

var currentDate = new Date();
var a = currentDate.getTime();

function test() {
    var currentDate = new Date();
    var b = currentDate.getTime();
var c = b - a;
    if (c > 900) {
        //Tab does not have focus.
    } else {
        //It does
    }
    a = b;
    setTimeout("test()",800);
}



setTimeout("test()",1);
  • 2
    I don't like the idea of using intervals for something that should be evented. And note, you should be using `setTimeout(test, 800)`. If you give it a string, it will `eval()` it, which is much much slower. – fent Mar 17 '12 at 11:30