V4 : back-button doesn't exit app [solved--Tutorial]

I want the app to close on the home page when the hardware back-button is triggered.
It doesn’t.
1/ Is it a normal behaviour or did I do something wrong ?
2/ I tried this :

backButtonEvent(){
    this.platform.backButton.subscribe(()=>{
      console.log ('exit');
      navigator['app'].exitApp();
    })

It works, but it works also in the other pages… so I can’t go back to the home page, I close the app.
Is there a way to just apply this behaviour when I’m on the home page?

2 Likes

Have you tried using paired lifecycle events (such as ionViewDidEnter and ionViewWillLeave) to register and deregister this action?

I thought about doing it, but I have to do it in every page…

So I wondered if someone had a better idea…

This issue is on the roadmap of the ionic team : https://github.com/ionic-team/ionic/issues/16611

Thanks anyway, I’ll try that untill the framework has treated this issue.

Le mar. 11 déc. 2018 à 19:42, Robert Coie ionicframework@discoursemail.com a écrit :

I don’t see why, based on what you’ve said here. Why isn’t just the home page sufficient?

Because I’m stupid… so obvious…
Thanks! I’ll try.

Here is the solution : in homepage.ts

ionViewDidEnter(){
      this.subscription = this.platform.backButton.subscribe(()=>{
          navigator['app'].exitApp();
      });
}

ionViewWillLeave(){
      this.subscription.unsubscribe();
}
13 Likes

How can i import the “navigator” property?

I don’t know… I looked in my file, no special import…Don’t remember where I got it.

navigator is a global variable

prosenjit_barui and trollanfer Thank you!

work for me in ionic 4 mantap

Hi… I am getting run time error “ERROR TypeError: Cannot read property ‘exitApp’ of undefind” when I use below code for back button
ionViewWillLeave() {
if (this.commonService.checkLogin) {
if (this.router.url === ‘/app-landing’) {
// navigator[‘app’].exitApp();
}
else if (this.router.url === ‘/login’) {
navigator[‘app’].exitApp();
}
}

Anything wrong with my code?

You should credit apropos with the solution since they clearly steered you in the right direction.

how did you declare subscription?

subscription : any ;

Le mar. 28 mai 2019 à 08:28, Krima via Ionic Forum ionicframework@discoursemail.com a écrit :

I do it like this in my App component

private setAndroidBackButtonBehavior(deviceInfo: DeviceInfo): void {
    if (deviceInfo.platform == "android") {
      this.platform.backButton.subscribe(() => {
        if (window.location.pathname == "/home") {
          navigator['app'].exitApp();
        }
      });
    }
  }
1 Like

Is Navigator is A variable or interface,
How can i declare navigator…?

This worked for us. Thanks!!