Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTML5: implementation of PageVisibility API
<script type="text/javascript">// <![CDATA[
var timer = 0;
//timeout value when the page is visible
var PERIOD_VISIBLE = 1000;
//timeout value when the page is NOT visible
var PERIOD_NOT_VISIBLE = 2000;
//returns whether the page is hidden or not
//not implemented on all browsers yet
function getHiddenState() {
if(document.hidden || document.webkitHidden || document.msHidden || document.mozHidden ) {
return true;
} else {
return false;
}
}
//returns whether the page is hidden or not
//not implemented on all browsers yet
function getVisibilityState() {
if(undefined!=document.visibilityState) {
return document.visibilityState;
} else if(undefined!=document.webkitVisibilityState) {
return document.webkitVisibilityState;
} else if(undefined!=document.mozVisibilityState) {
return document.mozVisibilityState;
} else if(undefined!=document.msVisibilityState) {
return document.msVisibilityState;
} else {
return "browser not yet supported";
}
}
//Depending on visibility, set the delay value
function getDelay() {
if(getHiddenState()) {
return PERIOD_NOT_VISIBLE;
} else {
return PERIOD_VISIBLE;
}
}
//Loaded when body loads
function onLoad() {
timer = setInterval(logTime, getDelay());
//Events
//Not implemented on all browsers yet
document.addEventListener("visibilitychange",visibilityChanged);
document.addEventListener("webkitvisibilitychange", visibilityChanged);
document.addEventListener("msvisibilitychange", visibilityChanged);
}
//Function fired when visibility changes
function visibilityChanged() {
clearTimeout(timer);
timer = setInterval(logTime, getDelay());
}
//Logs the current time and page visibility
function logTime() {
var currentTime = new Date();
var visibilityState = getVisibilityState();
var newLine = "
<li>"+currentTime.getTime()+" ("+visibilityState+")</li>
";
document.getElementById("time").innerHTML = document.getElementById("time").innerHTML + newLine;
}
// ]]></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.