可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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