3

I'm trying to detect when a user switches away from the current browser tab, to another tab. Listening for window.onblur works well in firefox for detecting when the user switches focus to another window, but it doesn't seem to fire when the user switches to another tab. However, it seems that onfocus is fired when switching to the tab in question, from another tab.

Is there a way to detect when the user switches away from the current tab?

Scotty Allen
  • 12,897
  • 9
  • 38
  • 51
  • **Update:** As of 2013 all major browsers provide support for the so-called [visiblity API](https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API?redirectlocale=en-US&redirectslug=DOM/Using_the_Page_Visibility_API). See here for a sample: http://stackoverflow.com/a/19519701/603003 – ComFreek Oct 23 '13 at 14:07

2 Answers2

8

Apparently in Firefox it'll work for tab switching if you use document.onBlur instead of window.onblur for the event handler.

Amber
  • 507,862
  • 82
  • 626
  • 550
3

This example code seemed to work for me. I edited the code to display an alert box when I switched tab (please dont do it). It resulted in a infinite loop ;-) and had to close FF using task manager.

Source : http://www.thefutureoftheweb.com/blog/detect-browser-window-focus

function onBlur() {
    document.body.className = 'blurred';
};
function onFocus(){
    document.body.className = 'focused';
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}
Shoban
  • 22,920
  • 8
  • 63
  • 107
  • @maksymko – That's called [conditional compilation](http://msdn.microsoft.com/en-us/library/7kx09ct1%28v=VS.80%29.aspx). – Marcel Korpel Jul 06 '10 at 00:06