Check if window has focus
Why not use the hasFocus method e.g.
if (document.hasFocus()) {
...
}
If you need to handle iframe
's as well then your check just becomes either or e.g.
function isFocused() {
return document.hasFocus() || document.getElementById('iframe').contentWindow.document.hasFocus();
}
You can use document.visibilityState
to know whether the page is in focus or not.