I know that the iPhone stops javascript from running when an app is sent to the background (ie pressing the home button while the app is running), but I would like to be able to detect if this has happened when the javascript starts up again when the app is reactivated.
One solution I’ve been trying is to have an iterator constantly running to “check in” and then running a check against that to tell if the app has gone to background.
var lastCheckinTime = new Date().getTime();
function checkin(){
lastCheckinTime = new Date().getTime();
}
setIterator( checkin, 1000 );
// Later, some code that needs to know if iphone went to background
var now = new Date().getTime();
if( (now - lastCheckinTime) > 1100 ) {
// run sent to background code
Is there a better way to do this? The problem I’ve found with this method is that it doesn’t work if the user quickly closes and reopens the app, but I haven’t figured out a better way of detecting this yet.
You can use the ‘pageshow’ event. Visit this page on your phone, http://jsfiddle.net/vbuDh/
This will fire anytime the tab gains focus, or mobile Safari is reactivated on this page.