当从后台切换回Safari时,如何在iOS webapp中检测? [英] How to detect in iOS webapp when switching back to Safari from background?

查看:271
本文介绍了当从后台切换回Safari时,如何在iOS webapp中检测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何构建一个能够监控页面何时获得焦点的网页,尤其是当Safari在后台并且用户将Safari切换回前台时。

How can I build a webpage which is able to monitor when the page gets the focus, especially when Safari is in the background and the user switches Safari back to the foreground.

以下代码在iPhone上切换到Safari时不会触发事件

The code below does not fire the event when switching to Safari on an iPhone

<html>
  <head>
    <script type="text/javascript">
      window.onfocus = function() { alert("onfocus"); };
    </script>
  </head>
  <body>

    Main text

  </body>
</html>

根据 http://www.quirksmode.org/dom/events/index.html :当窗口获得焦点时,Safari iPhone不会触发事件。

According http://www.quirksmode.org/dom/events/index.html : Safari iPhone does not fire the event when the window gains the focus.

所以我的问题仍然是:如何通过在Safari for iPhone的网页上使用javascript来检测窗口是否获得焦点?

So my question is still: how to detect by using javascript on a webpage within Safari for iPhone that the window receives the focus?

推荐答案

我相信当应用程序进入后台时,计时器(setInterval())会被暂停。你可以这样做:

I believe timers (setInterval()) are suspended when the app enters the background. You could do something like:

var lastFired = new Date().getTime();
setInterval(function() {
    now = new Date().getTime();
    if(now - lastFired > 5000) {//if it's been more than 5 seconds
        alert("onfocus");
    }
    lastFired = now;
}, 500);

您可能需要调整这些时间间隔以满足您的需求。

You may need to adjust those time intervals to suite your needs.

但是,最有可能的是,如果它足够长,需要刷新(几天),safari可能会重新加载页面,因为内存不足。

But, most likely, if it has been long enough to need a refresh (a few days) safari will probably reload the page because it is out of memory.

这篇关于当从后台切换回Safari时,如何在iOS webapp中检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆