页面隐藏和页面显示事件不能按预期在ios chrome上正常工作
Apple文档列出了可用的iOS浏览器事件: https : //developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html
“pagehide”和“pageshow”事件似乎在safari上运行良好,但是在chrome上它只能在页面加载和卸载时使用。 它不适用于:
1)按主页button,即发送铬到背景
2)切换标签
下面是一个小的JavaScript代码片段,你可以用它来validation它:
<script type="text/javascript"> window.addEventListener("pageshow", function(evt){ alert('show'); }, false); window.addEventListener("pagehide", function(evt){ alert('hide'); }, false); </script>
我能做些什么来检测铬是否被发送到后台。 一旦chrome返回到前台,我需要清除setTimeout计时器。 任何解决方法?
以下是工作代码:
<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);
你可以在这里find更多的细节: http : //aawaara.com/post/74543339755/smallest-piece-of-code-thats-going-to-change-the-world
页面隐藏和页面显示不是你想要完成的事情。
相反,使用visibilitychange
事件结合document.hidden
或document.visibilitystate
,这应该做你想要的。
这只适用于支持的浏览器 – 迄今为止包括Chrome浏览器,但不是Safari(还)。 所以为了安全起见,我会在visibilitychange
上调用clearTimers()
,并且只有在没有定义document.visibilitystate的情况下,才能在pagehide
调用它。
看到:
MDN:visibilitychange事件
MDN:使用页面可见性API
页面可见性 – W3C推荐,2013年10月