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.

Leave a Comment