Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect browser focus on mobile devices?

The application I'm developing is built around jQuery Mobile and some Ajax to refresh parts of the page. Like sites that use automatic refresh, I want to stop the refresh after some condition (time/visibility/etc.) so my server isn't bombarded with unneeded requests. The application has a status screen that is commonly checked by the user, and ideally my scripts would know that the browser window has come into focus and it would be a good time to refresh. I've done this before in desktop webapps, but I'm noticing a lot of variation on the mobile side between different platforms and browsers, for example:

  • window.onfocus() does/n't fire when the browser gains focus
  • window.onfocus() does/n't fire when tabs are switched in a browser
  • Javascript is/n't suspended between tab switches and/or switches away from browser

The best I've been able to do so far is a set of heuristics that look at available events + when there was detected user interaction with the page, but it's clunky and results in cases where the user jumps back to the page and has to manually refresh. Not great.

Any clever techniques for solving this?

like image 733
LVB Avatar asked Jan 04 '12 19:01

LVB


1 Answers

If you just want to know if browser window has been out of focus, use the requestAnimationFrame function.

window.requestAnimFrame = window.requestAnimationFrame ||
                          window.mozRequestAnimationFrame || 
                          <add browsers here>

Then in your code

var lastupdate = new Date()
(function loop() {
      var now = new Date();

      if ( now - lastupdate > <some treshold like 1 second> ) {
          // browser was suspended and did come back to focus
      }
      lastupdate = now;

      window.requestAnimFrame(loop);
})();

Trick is, that browsers do not give animation frame if tab or window is out of focus. Normal setInterval and setTimeouts will still work. This loop will run continously when window is on focus, but overhead is minimal, it's called maybe 3-5 times per second in mobile devices.

like image 187
Teemu Ikonen Avatar answered Nov 15 '22 17:11

Teemu Ikonen