views:

26

answers:

1

I'd like to be able to mute activity of my app if I can detect that the page is no longer focused. For instance, if the page is in a background tab or another app has focus, I'd like to disable a constantly polling script or switch modal notifications to the new HTML5 notifications API.

Is there any way to get this with JS, and if so, which browsers are supported?

PS - I've seen this, but don't know if it would work for what I'm looking to do. Anybody have any insight?

+1  A: 

You can listen for the blur event on your window, then for when the user comes back, you can use the focus event:

Here's an example in jQuery:

$(window).blur(function() {
    disableStuff();
    //...
}).focus(function() {
    enableStuff();
    //...
});

Or in pure JavaScript:

window.onblur = function() {
   disableStuff();
};
window.onfocus = function() {
   enableStuff();
};
Jacob Relkin
Awesome, I'll check this out tomorrow!
mattbasta
It works! Beautiful!
mattbasta