Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 592
fent Avatar asked Apr 27 '10 11:04

fent


People also ask

How do I know if my browser tab is in focus?

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 you check if a window is focused?

Use the document. hasFocus() method to check if a window has focus, e.g. if (document. hasFocus()) {} . The method returns a boolean value indicating whether the document or any element in the document has focus.


1 Answers

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.

like image 165
ninjagecko Avatar answered Sep 28 '22 23:09

ninjagecko