0

I have an iPhone webapp that uses a cache manifest to work offline and add the webapp to my Home screen. What I would like to find is a way to detect that the app is exiting so I can do some housekeeping and save some data.

If I am running as a web page in Safari, window.onunload does this for me, but this event does not happen when running from the Home screen.

ghenne
  • 1,903
  • 2
  • 19
  • 29

3 Answers3

1

I tested the pagehide event using the below code and found that it works well for detecting whether the user navigated to another link or simply opened a new tab when you are in safari.

However, if you are in a web app saved to your homescreen (like you describe) then the pagehide event is useless for telling if the web app was closed.

Depending on what you need specifically, you can work around this limitation by saving data to localStorage and then checking the localStorage when the app opens again. Then you can perform any extra work that may need to be done before the app fully starts again.

function myLoadHandler(evt)
{
  if (evt.persisted) {
    alert('user returns to page from another tab');
    return;
  }
  alert('loading new page');
}

function myUnloadHandler(evt)
{
  if (evt.persisted) {
    alert('user goes to new tab');
    return;
  }
  alert('user truly leaves the page');
}

if ("onpagehide" in window) {
  window.addEventListener("pageshow", myLoadHandler, false);
  window.addEventListener("pagehide", myUnloadHandler, false);
} else {
  window.addEventListener("load", myLoadHandler, false);
  window.addEventListener("unload", myUnloadHandler, false);
}
cruzanmo
  • 747
  • 8
  • 8
0

I have an answer. It's not what we were hoping for.

The technical definition of unload from http://www.w3.org/TR/DOM-Level-2-Events/events.html is:

The unload event occurs when the DOM implementation removes a document from a window or frame. This event is valid for BODY and FRAMESET elements.

I also got a reply from some in the know at Apple: "Unfortunately, I haven't been able to find an event that fires when the Home button is clicked! I think the most appropriate event for this might be the pagehide event. This event actually does fire in Safari on iOS when you switch to the "tabs" view to open a new page, but not when you click the home screen icon :-("

ghenne
  • 1,903
  • 2
  • 19
  • 29
-2

In iOS3 or multitasking unsupported devices/app, you can do the housekeeping in applicationDidTerminate method.

In iOS4 and multitasking supported devices/app, you can do the housekeeping in applicationDidEnterBackground method. It's best to implement the applicationDidTerminate method as well just in case iOS decide to remove your app from memory, applicationDidTerminate will be called in your app.

Cheers.

Seyther
  • 652
  • 4
  • 6