Apple documentation lists down the available iOS browser events here: https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html
The 'pagehide' and 'pageshow' events seem to work fine on safari, but on chrome it only works on page load and unload. It doesn't work on:
Pressing the home button, i.e. sending Chrome to background
Switching tabs
Below is a small Javascript snippet that you can use to verify it:
<script type="text/javascript">
window.addEventListener("pageshow", function(evt){
alert('show');
}, false);
window.addEventListener("pagehide", function(evt){
alert('hide');
}, false);
</script>
What can I do to detect whether chrome was sent to background or not. I need to clear a setTimeout timer as soon as chrome is brought back to foreground. Any workarounds?
Below is the working code:
<script type="text/javascript">
var heartbeat;
var lastInterval;
function clearTimers() {
clearTimeout(heartbeat);
}
function getTime() {
return (new Date()).getTime();
}
function intervalHeartbeat() {
var now = getTime();
var diff = now - lastInterval - 200;
lastInterval = now;
if(diff > 1000) { // don't trigger on small stutters less than 1000ms
clearTimers();
}
}
lastInterval = getTime();
heartbeat = setInterval(intervalHeartbeat, 200);
You can find more details here: http://aawaara.com/post/74543339755/smallest-piece-of-code-thats-going-to-change-the-world
Pagehide and pageshow aren't the events you need for what you're trying to accomplish.
Instead, use the visibilitychange event in combination with document.hidden or document.visibilitystate, which should do exactly what you want.
This'll only work on supported browsers - which to date includes Chrome, but not Safari (yet). So to be safe, I'd call clearTimers() on visibilitychange, and fall back to calling it on pagehide only if document.visibilitystate is not defined.
See:
MDN: visibilitychange event
MDN: Using the Page Visibility API
Page Visibility - W3C recommendation, October 2013
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With