Is it possible, in JavaScript, to detect when the screen is turned off in the Android & iOS browsers
I just found a pretty good solution for my use case:
function getTime() { return (new Date()).getTime();}var lastInterval = getTime();function intervalHeartbeat() { var now = getTime(); var diff = now - lastInterval; var offBy = diff - 1000; // 1000 = the 1 second delay I was expecting lastInterval = now; if(offBy > 100) { // don't trigger on small stutters less than 100ms console.log('interval heartbeat - off by ' + offBy + 'ms'); }}setInterval(intervalHeartbeat, 1000);
When the screen is turned off (or JS is paused for any reason), the next interval is delayed until JS execution resumes. In my code, I can just adjust the timers by the offBy
amount and call it good.
In quick testing, this seemed to work well on both Android 4.2.2's browser and Safari on iOS 6.1.3.
There is few options to check it:
Using Visibility API
Using
focus
andblur
events to detect browser tab visibility:
window.addEventListener("focus", handleBrowserState.bind(context, true));window.addEventListener("blur", handleBrowserState.bind(context, false));function handleBrowserState(isActive){ // do something}
- Using timers, as mentioned above
Found a nice function here:
http://rakaz.nl/2009/09/iphone-webapps-101-detecting-essential-information-about-your-iphone.html
(function() { var timestamp = new Date().getTime(); function checkResume() { var current = new Date().getTime(); if (current - timestamp > 4000) { var event = document.createEvent("Events"); event.initEvent("resume", true, true); document.dispatchEvent(event); } timestamp = current; } window.setInterval(checkResume, 1000);})();
To register for event:
addEventListener("resume", function() { alert('Resuming this webapp');});
This is consistent with Cordova which also fires the resume
event.