Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event for when user switches browser tabs

I'm looking for an event which will fire whenever the user switches away from the page to another tab, and another event which fires when the user switches back to the tab again.

window.onblur and window.onfocus don't seem to work correctly across all browsers

Is there a proxy I could look at in order to synthesize this event?

like image 901
EoghanM Avatar asked Jun 24 '09 14:06

EoghanM


2 Answers

You can also try and use VisibilityAPI.

document.addEventListener("visibilitychange", function() {     if (document.hidden){         console.log("Browser tab is hidden")     } else {         console.log("Browser tab is visible")     } }); 

See also here on Stackoverflow (possible duplicate)

like image 116
ronapelbaum Avatar answered Sep 22 '22 08:09

ronapelbaum


You might try using a framework, such as MooTools or jQuery which provide cross-browser support. They should be able to detect with more reliability the blur and focus events for the browser window.

I personally have used jQuery with much success:

$(window).blur(function(e) {     // Do Blur Actions Here }); $(window).focus(function(e) {     // Do Focus Actions Here }); 
like image 22
DanO Avatar answered Sep 22 '22 08:09

DanO