← Back to Posts

Javascript and Cross-browser Window focus

It is a common requirement in today’s highly interactive web applications to keep track if the browser window is currently in focus. Let me tell you one thing. If you take a look at the browser events and the very limited documentation, you might be tempted to believe that you are in safe hands. But thats not the case.

Catching the onblur and onfocus events is the most recommended way to know when a window gains or loses focus. But this does not work in all cases. The onfocus event is triggered correctly in almost all browsers. But onblur on the other hand is highly unpredictable. In Internet Explorer, every onfocus event is immediately followed by an onblur event even though the window is still in focus. On Firefox, the onblur will not be trigerred if the active element of the window is of input type.

Solution: IE has its custom events which works fine for it namely focusin and fosucout. For firefox, we need to check whether the active element has changed.

var isIE = (navigator.appName == "Microsoft Internet Explorer");
var hasFocus = true;
var active_element;

function setFocusEvents()	{
	active_element = document.activeElement;
	if (isIE)	{
		document.onfocusout = function() {	onWindowBlur();	      }
		document.onfocusin = function()	 {	onWindowFocus();     }
	}	else	{
		window.onblur = function()	  {	onWindowBlur();	         }
		window.onfocus = function()	 {	onWindowFocus();       }
	}
}

function onWindowFocus()	{
	hasFocus = true;
}

function onWindowBlur()	{
	if (active_element != document.activeElement) {
		active_element = document.activeElement;
		return;
	}
	hasFocus = false;
}

NB: I have tested mostly on IE 6+ and Firefox. So you might find my method incomplete for other browsers.

Update: This post has been updated (corrected) as per Lucent’s comment.