The code below works as expected in all browsers. It correctly displays the current Page visibility as the document title. For instance, if the browser is minimized or the user clicks on a different tab, document becomes hidden and the title change accordingly. When the user returns to the page, the document becomes visible and the title adjusts as well.
However Chrome exhibits a peculiar behavior: it respond correctly to minimize, maximize (restore) events, adjusting visibility accordingly. It also recognizes when the user clicks on a different tab, exiting the current, the very first time, setting the document title to hidden. However, when user returns to document from another tab, nothing happens. Why does Chrome not recognize the page is visible when retuning to it from a different Tab? Is there a way to fix this or maybe a better way to do it?Thanks, your help is much appreciated.
<script type="text/javascript">
var visibility;
function init() {
if (typeof document.hidden != "undefined" || typeof document.msHidden != "undefined" ||
typeof document.webkitHidden != "undefined" || typeof document.mozHidden != "undefined")
{
if (typeof document.hidden != "undefined")
{
visibility = !document.hidden;
if (addEventListener) document.addEventListener("visibilitychange", visibilityChange);
}
else if (typeof document.msHidden != "undefined")
{
visibility = !document.msHidden;
if (addEventListener) document.addEventListener("msvisibilitychange", visibilityChange);
}
else if (typeof document.webkitHidden != "undefined")
{
visibility = !document.webkitHidden;
if (addEventListener) document.addEventListener("webkitvisibilitychange", visibilityChange);
}
else if (typeof document.mozHidden != "undefined")
{
visibility = !document.mozHidden;
if (addEventListener) document.addEventListener("mozvisibilitychange", visibilityChange);
}
}
else displayWarning();
}
function displayWarning() {
alert("Warning!");
}
function visibilityChange() {
if (typeof document.hidden != "undefined") visibility = !document.hidden;
else if (typeof document.msHidden != "undefined") visibility = !document.msHidden;
else if (typeof document.webkitHidden != "undefined") visibility = !document.webkitHidden;
else if (typeof document.mozHidden != "undefined") visibility = !document.mozHidden;
handleVisibility();
}
function handleVisibility() {
if (visibility) {
document.title="Visible";
}
else {
document.title="Hidden";
}
}
init();
</script>