Is there a reliable way to determine if a browser tab or window is inactive or not in focus?

browser, cross-browser, javascript

Solution

The above code is working fine in `Safari v3.0.4` (WebKit 530+), the bug has been resolved it seems. I've checked it in `Google Chrome v3.0.195.27` and it has the same Safari bug, although it has a newer version of WebKit.

Problem

I've got a javascript timer that is making XMLHTTP requests on a constant basis (once every 10 seconds). I'd love to be able to pause the timer when the window or tab loses focus. I'm fully aware of the `onFocus` and `onBlur` events on the `window` object, but they don't fire reliably across all browsers. For instance, in Safari, tabs don't trigger the events. Simple code below distills the functionality I'm looking for: ``` <html> <head> <title>Testing</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js"></script> </head> <body> <div id="console"></div> <script type="text/javascript"> window.onfocus = function(event) { $('console').insert('Window gained focus<br />'); } window.onblur = function(event) { $('console').insert('Window lost focus<br />'); } </script> </body> </html> ``` Does anyone out there have a technique for determining when a browser window or tab loses/gains focus that works across across all popular browsers?

Original source

Related problems