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 los
<script>
// Adapted slightly from Sam Dutton
// Set name of hidden property and visibility change event
// since some browsers only offer vendor-prefixed support
var hidden, state, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
state = "visibilityState";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
state = "mozVisibilityState";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
state = "msVisibilityState";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
state = "webkitVisibilityState";
}
// Add a listener that constantly changes the title
document.addEventListener(visibilityChange, function() {
document.title = document[state];
}, false);
// Set the initial value
document.title = document[state];
</script>
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.
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.
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.
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.
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.