Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

javascript - How to detect in iOS webapp when switching back to Safari from background?

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.

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>

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...