Ionic run function before app closes

15,043

Solution 1

You can check this events list from Cordova docs:

https://cordova.apache.org/docs/en/5.4.0/cordova/events/events.html

In particular Pause event:

The event fires when an application is put into the background.

document.addEventListener("pause", yourCallbackFunction, false);

Solution 2

This code works in ionic2 native app exit and in the browser as well. In the browser, this happens when the URL reload button is pressed or the browser tab is closed.

platform.pause.subscribe(e => {
  this.OptionsSave();
});

window.addEventListener('beforeunload', () => {
  this.OptionsSave();
});
Share:
15,043
Admin
Author by

Admin

Updated on July 20, 2022

Comments

  • Admin
    Admin almost 2 years

    Is there some kind of function that I can call that listens to whether the app is about to exit, or close or go into the background.. Basically any event that means "the user has stopped using the app"?

    I'm my app I build up a 'user log' that tracks the user as they are navigating through the app. Instead of sending little pieces of data constantly to the server as these events occur, I want to send off the whole batch in one go just before the user stops using the app (again, whether that means closing the app completely, sending it to the background etc.)

    And lastly, if such a function does indeed exist.. where do you put that function? In your app.js? Or do you have to put that listener in every single controller of your app?

  • Admin
    Admin over 8 years
    thanks, and where would you put that function? App.js or have a listener like that in each of your controllers?
  • beaver
    beaver over 8 years
    IMO you can add those event listeners in app.js inside the app.run() function
  • billy_comic
    billy_comic over 7 years
    This works well in the case that someone is swiping out of the app, but is there a way to call a function when I minimize or switch to a different app?
  • Sunil Rawat
    Sunil Rawat over 6 years
    Did you found any solution for above, I am also need same event, to update a field value in db if app closed by user.
  • Dominik
    Dominik over 3 years
    The pause event als also run on app standby or some other actions which causes a focus blur. You can see a lot of logs in pause and resume events. I guess a real before-app-closed event does not exist. Because the exit should not delayed by the application. It's a controlled by the OS (and user). Running code in such event would be time criticial.