Detect when app is force closed?

I understand that we can use:

document.addEventListener(‘resume’, ( ) => {

});
document.addEventListener(‘pause’, ( ) => {

});

To detect when the app is minimized or is active, but is there anyway to detect and execute a code when the app is force closed? Like NgOnDestroy or something similar?

You could try some native javascript events like:
window.onunload
window.onbeforeunload

But keep in mind, what should happen if you put your app in background --> so your app is paused. And you close your app in pause-mode (via process explorer/manager? No code gets executed anyways even if there is a ‘close’ event.

But maybe there should be something like “graceful” exit :smiley:

This works in ionic2 in browser when the URL reload is pressed.


    window.addEventListener('beforeunload', () => {
      this.OptionsSave();
    });
5 Likes

Here is the same version using Observable:

Observable.fromEvent(window, 'beforeunload').subscribe(event: Event => this.unsubscribeFromSignals());

This works like a charm