Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript event for mobile browser re-launch or device wake

Morning all, I'm looking for some kind of Javascript event I can use to detect when a mobile browser window regains focus, after either a user closes/minimizes their browser (to go back to a home screen/different app), or if the device resumes from sleep (either the user powering it off, or it going to sleep after a screen timeout).

I'd like to be able to find a single event that works for everything, but I know that's unlikely! The pageshow event works for iOS devices, but it's rather sketchy for use with everything else. I've tried focus and DOMActivate but neither of them seem to have the desired effect.

The page may not always have form elements on it, and I don't really want the user to have to touch the page again to trigger the event.

The requirement for such an event is caused by our code periodically checking for new content by making XHR requests. These are never sent when the browser is asleep, so we never get new content to restart the timeouts.

Thanks for any help you guys may be able to provide!

like image 829
brins0 Avatar asked Dec 10 '12 09:12

brins0


1 Answers

We had a similar issue and solved it something like this:

var lastSync = 0;
var syncInterval = 60000; //sync every minute

function syncPage() {
  lastSync = new Date().getTime(); //set last sync to be now
  updatePage(); //do your stuff
}

setInterval(function() {
  var now = new Date().getTime();
  if ((now - lastSync) > syncInterval ) {
    syncPage();
  }
}, 5000); //check every 5 seconds whether a minute has passed since last sync

This way you would sync every minute if your page is active, and if you put your browser in idle mode for over a minute, at most 5 seconds will pass before you sync upon opening the browser again. Short intervals might drain the battery more than you would like, so keep that in mind when adapting the timings to you needs.

like image 53
SirMarino Avatar answered Nov 14 '22 13:11

SirMarino