Ionic 4/5: exit from the app pressing back button

Viewed 6753

I need to exit from the app when the back button is pressed only in a certain page; in particular, let's say I have I have the app.component.ts and I have a page called HomePage. In app-routing.module.ts I have this routes:

const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './public/home/home.module#HomePageModule' }
];

So whever the user opens the app, it will see the HomePage as first page. If the user presses the back button, now it reloads the same page forever; I want to catch that pressing and exit the app. I've tried to use this in home.page.ts, but nothing happens:

backButtonSubscription: any;
this.backButtonSubscription = this.platform.backButton.subscribe(async () => {
console.log('lets exit!');
  navigator['app'].exitApp();
  });

Even the console.log is printed, as if the event is not caught. I've also tried with this:

 this.platform.backButton.subscribeWithPriority(99999, () => {
        navigator['app'].exitApp();
 });

but the result is the same, so I'm wondering how it can be solved. I've found a lots of questions online, but there's no explanation that seems to solve this issue or to give a workaround.

Thanks for your help!

3 Answers

if you are using ionic 4 angular . try this in AppComponent -> initializeApp add

this.platform.backButton.subscribeWithPriority(0, () => {
navigator[‘app’].exitApp();
});

here is an example

initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.platform.backButton.subscribeWithPriority(0, () => {
        navigator['app'].exitApp();
       
     });
    });
  }

in my case im using capacitor (ionic 5), try this if you're using capacitor too

import { Plugins } from '@capacitor/core';
const { App } = Plugins;

initializeApp() {
  App.addListener('backButton', () => {
    App.exitApp();
  });
}

Ionic 5. Another option its to use Platform, for me it woks well in case of using tabs:

p.s. better to use "init" service instead of app.component.ts to keep app init flow clean and obvious

constructor(
    private platform: Platform,
    private router: Router
) {
    this.platform.backButton.subscribeWithPriority(-1, () => {
        const url = this.router.url;
    
        if (url === '/tabs/not-home') {
            this.router.navigate(['/tabs/home']);
        } else if (url === '/tabs/home') {
            App.exitApp();
        }
    });
}
Related