Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pagehide and pageshow events don't work as expected on ios chrome

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:

  1. Pressing the home button, i.e. sending Chrome to background

  2. 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?

like image 969
amit_saxena Avatar asked Jan 23 '14 14:01

amit_saxena


2 Answers

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

like image 87
amit_saxena Avatar answered Oct 06 '22 18:10

amit_saxena


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

like image 32
Doin Avatar answered Oct 06 '22 18:10

Doin