Disable Android hardware back button on Ionic

#1

Hello guys,

How can I disable hardware back button of Android on Ionic 3?

I looked this up and many examples for Ionic 1 and 2 showed up but I’m not sure if their code is still valid on Ionic 3.

I’m trying to disable hardware back button permanently on my app because this app I’m building now is not supposed to be navigated with a back button.

Thanks

#2

Ionic 2 code should work just fine.

1 Like
#3

Thanks for your response Chris,

My current code isn’t working:

 this.platform.ready().then(() => {
       document.addEventListener('backbutton', () => {
        if (!this.navCtrl.canGoBack()) {
          this.platform.exitApp()
          return;
        }
        this.navCtrl.pop()
      }, false);
       });

It still exits my app when I click on back button.
Would you please help applying this properly?

Thanks,

#4

It would seem telling that your code has a line that says exitApp().

1 Like
#5

Yes… I wonder how to null that action.

#6

an explanation on how to handle it is in The ionic documentation

a quick example:

import { Component } from ‘@angular/core’;
import { IonicPage, NavController, Platform } from ‘ionic-angular’;

@IonicPage()
@Component({
  selector: 'page-categories',
  templateUrl: 'categories.html',
})
export class CategoriesPage {
  categories;

  constructor(
  public navCtrl: NavController, 
  public navParams: NavParams,
  public platform: Platform
  ) {
      platform.registerBackButtonAction(() => {
        //sometimes the best thing you can do is not think, not wonder, not imagine, not obsess. 
        //just breathe, and have faith that everything will work out for the best.
      },1);
  }
}
4 Likes
#7

Hi, @jamesharvey

I think this will help you, try below tutorial:

thanks

2 Likes
#8

this didn’t work for me

#9

Thanks. It worked for me. I just had to remove not(!) in condition. It is just for future reference.

this.platform.ready().then(() => {
       document.addEventListener('backbutton', () => {
        if (this.navCtrl.canGoBack()) {
          this.platform.exitApp()
          return;
        }
        this.navCtrl.pop()
      }, false);
       });
#10

You can use the method ionViewCanLeave(), as follows:

ionViewCanLeave() {
  return {boolean};
}

Where the returned boolean can be a property like this.unlocked