Event for when user switches browser tabs

Solution 1:

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)

Solution 2:

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