Does anyone know what to use instead of hasFocus() for Chrome? I want to know when my Chrome tab has focus or not, so I can blink an alert message in the title.
Cheers
You could listen for the onfocus/onblur events and keep track of page state that way.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="output">
</div>
<script>
var has_focus = true;
function print(str) {
var out = document.getElementById('output')
out.innerText = out.innerText + "\n" + str;
};
window.onfocus = function() {
print('focus');
has_focus = true;
};
window.onblur = function() {
print('blur');
has_focus = false;
};
</script>
</body>
</html>
The page visibility API should do the trick: https://developer.mozilla.org/en-US/docs/DOM/Using_the_Page_Visibility_API
document.hidden
Returns true if the page is in a state considered to be hidden to the user, and false otherwise.
Of course, since this is a new API, you'll need to use different browser prefixes:
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
}
var isHidden = document[hidden];
// or even
var isFocused = !isHidden;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With