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

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

Apple documentation lists down the available iOS browser events here: https://developer.apple.com/library/safari/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?

回答1:

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



回答2:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!