How to access physical back button

Hello everyone, facing an problem with physical back button. want to give a alert message before getting out of the app by clicking physical back button. Using ionic 4. I need this functionality for a page other then the root page (Home Page).
Checked this link but did not understand how to implement.
https://forum.ionicframework.com/t/v4-back-button-doesnt-exit-app-solved-tutorial/149994

To do what you need first of all you have to always be listening to what your application does. In simple words, you tell the device to always be aware of when the back button is pressed, whether physical or virtual and that is done as follows:

import { Subscription } from 'rxjs';
import { AlertController } from '@ionic/angular';

subscripcion: Subscription;

constructor()
{
}

ngOnInit()
{
	this.subscripcion = this.platform.backButton.subscribe(()=>{
      //once you press the back button it will execute what you write of code here
	  this.ClosingApp();
    });
}

ngOnDestroy()
{
	//when you leave the current screen you stop listening to the back button button. You destroy the instance. this is a good practice
    this.subscripcion.unsubscribe();
}

async ClosingApp()
 {
    let alert = await this.alertCtrl.create({
      header: 'Confirm',
      message: 'Message to confirm!!!',
      buttons: [{
        text: "Exit",
        handler: () => { this.exitApp() }
      }, {
        text: "Cancelar",
        role: 'cancelar'
      }]
    })
    await alert.present();
 }
 
 exitApp()
 {
	//execute any code 
	this.navCtrl.navigateRoot('/login');
 }

Greetings and Happy Holidays

1 Like

I used this code to subscribe back button to close app.

  ionViewDidEnter(){

  document.addEventListener("backbutton", (e)=> {
         console.log("Back button");
         this.confirmClose()
  });
}


--------------
ionViewWillLeave(){
document.removeEventListener("backbutton", (e)=>{},false)
}
-------------

async confirmClose()
 {
    let alert = await this.alertCtrl.create({
      header: 'Confirm',
      message: 'Message to confirm!!!',
      buttons: [{
        text: "Exit",
        handler: async () => {
          await this.exitApp() 
       }
       }, {
        text: "Cancel",
        role: 'cancel'
      }]
    })
    await alert.present();
 }
--------
 exitApp() {
navigator['app'].exitApp();
}

I recommend never typing the word “function” inside the body of one, because it causes counterintuitive things to happen to execution context. Prefer arrow functions instead.

1 Like

Hi, tried with the code you have given but not working properly.Just changed a line in exitApp function.

exitApp()
{

   navigator["app"].exitApp();

}

The page sequence is like this-
diagram

I have written the code in page 1.
And the code is working in every page except page 1.

If I currently on page 3 and i pressed the back button, alert working but in the mean time page already move to page 2. Same thing happening in page 2 , if I clicked button in page to, gives the alert as well as move to page 1.

same thing is happening with your code, as i replied to cristsaavedra.
What is happening if press back button alert message popped but page already moved to backward. and alert shows in every page , I want only for a particular page.

Good morning, you could put the code you are using for your case and so we can replicate it.
The code that I put you I have implemented in an application already made so it seems strange what you tell me. We can also help you better.

Greetings and I remain attentive to your comments

trying to understand a little better what you explained a little higher I think I understood your problem and I think I will explain my code a bit.
in the first instance when entering page 1 after having made the corresponding login this call to the following function:


ngOnInit()
{
	this.subscripcion = this.platform.backButton.subscribe(()=>{
      //once you press the back button it will execute what you write of code here
	  this.ClosingApp();
    });
}

What it does is that it tells the device that it is always listening to the back button button every time it is pressed. Once this button is pressed the one that finally does the magic and that makes it wait for an answer is the following function:

async ClosingApp()
 {
    let alert = await this.alertCtrl.create({
      header: 'Confirm',
      message: 'Message to confirm!!!',
      buttons: [{
        text: "Exit",
        handler: () => { this.exitApp() }
      }, {
        text: "Cancelar",
        role: 'cancelar'
      }]
    })
    await alert.present();
 }

Once this function is executed, it will wait for an answer and will not continue processing anything else since as mentioned before, wait for a response from the user before changing the page or closing the application or minimizing the application or what you You need it so it seems quite strange to me what you indicate is that you are changing the page before waiting for the answer. If what you need is for the page to be changed or one page back after a positive response you have to place it in this portion of code:

handler: () => { //execute any function or code you need when the answer is yes  }

If the answer you receive is to cancel, it will not do anything and should keep you on the same page and not change anything since that is why you expect an answer with the await nomenclature:

let alert = await this.alertCtrl.create({

anyway I wait for your code to see what may be happening to you

Good after noon and wishing you a Happy new year.
Thanks for all your effort , I understand what this code does . You have mentioned inside the ClosingApp function a button Cancelar, can you tell me what to write( handler function) to prevent navigating backwards for a particular page(I my case other than home page) when user presses cancelar inside alert alert box.
Actually what is happening till now is, If I press Exit button inside alert , the app closes as I need , but when I clicking cancel button it navigating me backwards which I need to stop.
Please mention if you need further explanation.

Hi, I am almost their to achieve what I need I have added few line of code to ClosingApp function . I will explain -

this.subscripcion = this.platform.backButton.subscribe(()=>{

  if (this.router.url == '/streams-list' ){     

      this.ClosingApp();
   }

});

To stop listining to backbutton press on other pages and execute ClosingApp() , I have added if condition so that the function only executes when a user on ’ streams-list '.
//////////////////////////////////

async ClosingApp()
{
let alert = await this.alertController.create({
header: ‘Confirm’,
message: ‘Message to confirm!!!’,
buttons: [{
text: “Yes”,
handler: () => { this.exit() }
}, {

    text: "No",
    role: 'cancel',
    handler:()=>{

      this.router.navigate(['/streams-list']);
  }]
})
 alert.present();

}

When alert comes up if user presses ‘Yes’ button the app will go dismiss.
But when user presses cancel button what it does is prevent the app from getting dismiss. and remain in the same page that is “streams-list”.
Here comes the twist, when user press the hardware back button inside the ‘streams-list’ page it is taking me to the Login Page, meanwhile alert box remain open to choose Yes/no option.
Page sequence is like this -

Login page -> Stream-list-> other pages…
means alert box remain open at the same time navigates to login page.

1244/5000

Good morning and happy year to you too.
Regarding your query, it is rare for your application to go back to the other page when you click on the cancel button since that should not happen, it should remain on the same page and cancel the event, that’s why I mentioned you in the previous post that It seemed strange to me to do that since the function is waiting for a response from the user and if this is to cancel it does not continue doing anything and does not move beyond this. I will make a new project at this time to try to emulate what I could of code although I know it works because I have it implemented in an app that is already working.
With respect to the router.url that I saw that you added, this is only to know on which page you are currently. I don’t know if it’s a good idea to add code if you already know what page you are currently on. It is a bit redundant. I understand the logic because I use the way you try to do but I use it because a page can be called from different modules that in turn are different pages, so to know where it comes from I use the url router and depending on this It’s where I go back to the previous page. If what you are requiring is that is fine.

1 Like

Hi, it is working now.
Thanks for all your support. By the way which country are you from, I am from India, here it is evening 5.00 pm now.

I’m glad it works for you now. I was doing just the test code to upload it to git and you will try it. Here is 08:30 am GTM 03:00 Chile.

Good luck and have a happy year.

don’t forget to put your code on how you made it work so that it can serve others and mark your answer as a solution.

Here is my code,

getBackButtonClick(){

this.subscripcion = this.platform.backButton.subscribe(()=>{

   if ( this.router.url == '/home' ){ 

      this.ClosingApp();
   }

});

}
//////////////////////////////
async ClosingApp()

{

  let alert = await this.alertController.create({

  header: 'Confirm',

  message: 'Message to confirm!!!',

  buttons: [{

    text: "Yes",

    handler: () => { this.exit() }

  }, {

    text: "No",

    handler:()=>{

      

      this.navController.navigateRoot('/home');

      

    }

  }]

})

 alert.present();

}
//////////////////////////
exit()

{

navigator[“app”].exitApp();

}

///////////
ngOnDestroy()

{
this.subscripcion.unsubscribe();
}

The getBackButton() function is for listening hardware back button is pressed or not, if pressed than it will call the ClosingApp() , I wrote a if condition inside getBackButton() to cross check ClosingApp() function is called only when the user is on “home” page…

ClosingApp() is to display alert, if user press yes button inside alert box, it will simply exit the app. and if presses No than it will redirect to home page, i.e user remain on the home page.

ngOnDestroy() is for unsubscribing back button , so that the function is not called in other pages.

1 Like

Try this, But am not sure!!

platform.registerBackButtonAction(() => {
// get current active page
let view = this.nav.getActive();
if (view.component.name == “HomePage”) {
//Double check to exit app
if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
platform.exitApp(); //Exit from app
} else {
let toast = this.toastCtrl.create({
message: ‘Press back again to exit App’,
duration: 3000,
position: ‘bottom’
});
toast.present();
lastTimeBackPress = new Date().getTime();
}
} else {
// go to previous page
this.nav.pop({});
}
});

No. Never write anything that relies on names of classes, variables, or properties as strings. It will break in production.