views:

346

answers:

4

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"&gt;&lt;/script&gt;
  </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?

A: 

My previous desperate attempts to find such a thing have led me to conclude that there is no such animal.

Oh, how I would love to be wrong.

chaos
+2  A: 

There is another Stack Overflow question regarding this topic. They didn't address the tabbed browsing issue there. They do give a link which goes into some detail, although without using jquery.

http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active

I don't think focus/blur events work with tabbed browsing in Safari at all. Some people have suggested mouse events, like mouseleave/mouseenter for this.

I've got some UI issues like this myself, so if I discover anything I'll follow up here.

Mnebuerquo
A: 

One thing to consider is that tab focus/blur events being blocked by browser vendors is possibly a way to protect users. Some browsers allow alert()-style popups (and even, I believe, a focus() method) to cause a tab to regain focus. Blocking the focus/blur events for tab switching could be akin to protection against, for example, unrequested popups and window sizing/positioning/closing.

eyelidlessness
+2  A: 

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.

detj
You're correct that recent versions of Safari do handle this, and Chrome does not. I'm just going to say that for my purposes, support of 3 out of the top 4 ain't that bad.
Jim Fiorato
Chrome v3.0.195.38 is behaving strangely. It fires the events on tab switch but only when at least one window switch occurs.
detj