Skip to content Skip to sidebar Skip to footer

Is It Possible To Detect When A User Switches To A Different Browser Tab?

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

Solution 1:

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


Solution 2:

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;
}

Post a Comment for "Is It Possible To Detect When A User Switches To A Different Browser Tab?"