I have JavaScript that is doing activity periodically. When the user is not looking at the site (i.e., the window or tab does not have focus), it\'d be nice to not run.
This is really tricky. There seems to be no solution given the following requirements.
This happens because:
Given these restrictions, it is possible to implement a solution that combines - The page Visibility API - window blur/focus - document.activeElement
That is able to:
When the iframe has focus, your blur/focus events don't get invoked at all, and the page Visibility API won't trigger on alt+tab.
I built upon @AndyE's solution and implemented this (almost good) solution here: https://dl.dropboxusercontent.com/u/2683925/estante-components/visibility_test1.html (sorry, I had some trouble with JSFiddle).
This is also available on Github: https://github.com/qmagico/estante-components
This works on chrome/chromium. It kind works on firefox, except that it doesn't load the iframe contents (any idea why?)
Anyway, to resolve the last problem (4), the only way you can do that is to listen for blur/focus events on the iframe. If you have some control over the iframes, you can use the postMessage API to do that.
https://dl.dropboxusercontent.com/u/2683925/estante-components/visibility_test2.html
I still haven't tested this with enough browsers. If you can find more info about where this doesn't work, please let me know in the comments below.