Disable Hardware Back Button on certain condition

Hello :blush:

I am trying to perform a task but I can’t get it to work. I have a page that shows every time there is no internet connection and it has one button ‘Try Again’. If I clicked on the button ‘Try Again’ it will check the internet connection status, if there is an internet connection - it will remove the ‘No Internet Connection’ Page and it will return to the previous page BUT if there is no internet connection - the current view must stay on the page and the hardware back button should NOT execute its action. Here is my code for that:

    this.loadingSrvc.show();
    this.network.onConnect().subscribe(() => {
      setTimeout(() => {
        this.loadingSrvc.hide();
        this.navCtrl.pop();
      }, 3000);
    });
    
    this.network.onDisconnect().subscribe(() => {
      this.loadingSrvc.hide();
      // Code to Disable the Hardware Back Button.
    });

I’ve tried to look for a solution everywhere but I couldn’t find any that solves my problem. I hope that there is someone that could help me. Thank you in advance :heart_eyes:

HI,
this should help you Manage-hardware-backbutton

1 Like

If this works for u , Please mark as solution

1 Like

Hello :blush:.

I’ve tried applying your suggestion but it didn’t work on my case, here is my code.


    this.platform.registerBackButtonAction(() => { 
      if (!this.nav.canGoBack() || this.nav.getActive().name == 'NoInternetPage') {
        let alert = this.alertCtrl.create({
            title: 'Vidalia',
            message: 'Do you want to close the app?',
            buttons: [{
                text: 'Cancel',
                role: 'cancel',
                handler: () => {
                    console.log('Application exit prevented!');
                }
            },{
                text: 'Close',
                handler: () => {
                    this.platform.exitApp(); // Close this application
                }
            }]
        });
        alert.present();
      }
    });

I’ve tried removing this.platform.registerBackButtonAction(() => { } to test my condition and it is working fine, I guess there is something wrong with that particular code but I can’t figure it out. I would much appreciate it if you could help me out. Thank you :heart_eyes:

Hey :heart_eyes:. It is working now. Hehe. I just placed the code inside the construct instead of another function and I got it working. Thank you so much for your help :sparkling_heart:

I’m using Ionic 5 with Angular and the function this.platform.registerBackButtonAction doesn’t seem to exist anymore

1 Like

@edthernet can you try this for ionic 5.