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


#1

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?


Hardware back button with Ionic 4
#2

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


#3

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 :


#4

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


#5

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


#6

Here is the solution : in homepage.ts

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

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

#7

How can i import the “navigator” property?


#8

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


#9

navigator is a global variable


#10

prosenjit_barui and trollanfer Thank you!


#11

work for me in ionic 4 mantap


#12

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?