How to detect when a tab is focused or not in Chrome with Javascript? -
i need know if user viewing tab or not in google chrome. tried use events blur , focus binded window, blur seems working correctly.
window.addeventlistener('focus', function() { document.title = 'focused'; }); window.addeventlistener('blur', function() { document.title = 'not focused'; });
the focus event works weird, sometimes. if switch tab , back, focus event won't activate. if click on address bar , on page, will. or if switch program , chrome activate if tab focused.
2015 update: new html5 way visibility api (taken blowsie's comment):
document.addeventlistener('visibilitychange', function(){ document.title = document.hidden; // change tab text demo })
the code original poster gives (in question) works, of 2011:
window.addeventlistener('focus', function() { document.title = 'focused'; }); window.addeventlistener('blur', function() { document.title = 'not focused'; });
edit: of few months later in chrome 14, still work, user must have interacted page clicking anywhere in window @ least once. merely scrolling , such insufficient make work. doing window.focus()
not make work automatically either. if knows of workaround, please mention.
Comments
Post a Comment