Created
May 31, 2022 09:18
-
-
Save 4msar/c336c611a9832654b0fbde69868f0313 to your computer and use it in GitHub Desktop.
Determine the browser window is visible or not
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(callback) { | |
var hidden = "hidden"; | |
// Standards: | |
if (hidden in document) | |
document.addEventListener("visibilitychange", onchange); | |
else if ((hidden = "mozHidden") in document) | |
document.addEventListener("mozvisibilitychange", onchange); | |
else if ((hidden = "webkitHidden") in document) | |
document.addEventListener("webkitvisibilitychange", onchange); | |
else if ((hidden = "msHidden") in document) | |
document.addEventListener("msvisibilitychange", onchange); | |
// IE 9 and lower: | |
else if ("onfocusin" in document) | |
document.onfocusin = document.onfocusout = onchange; | |
// All others: | |
else | |
window.onpageshow = window.onpagehide | |
= window.onfocus = window.onblur = onchange; | |
function onchange (evt) { | |
var v = "visible", h = "hidden", | |
evtMap = { | |
focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h | |
}; | |
evt = evt || window.event; | |
if (evt.type in evtMap) | |
callback(evtMap[evt.type]); | |
else | |
callback(this[hidden] ? "hidden" : "visible"); | |
} | |
// set the initial state (but only if browser supports the Page Visibility API) | |
if( document[hidden] !== undefined ) | |
onchange({type: document[hidden] ? "blur" : "focus"}); | |
})(state => { | |
if (state == "visible") { | |
document.title = "Hello World!"; | |
} else { | |
document.title = "Hey come back!"; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment