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?