Disable back button on some of the views in ionic 4

Hi guys,

I want to disable the hardware back button on dashboard page. Back button need to work on remaining pages for navigation purpose except on dashboard page. If hardware back button was used on dashboard page it need to show close message and if again click on hardware back button then it needs to be closed.

I’ve used the below code in app.component.ts . It disabling hardware back button completely even in before/after login too.

I’m unable to get page name. Please give suggestons if any. Thanks in advance.

initializeApp() {
    this.platform.ready().then(() => {
      this.platform.backButton.subscribeWithPriority(9999, () => {
        document.addEventListener('backbutton', function (event) {
          event.preventDefault();
          event.stopPropagation();
          console.log('hello');
        }, false);
      });
      this.statusBar.styleDefault();
    });
  }
1 Like

Use this Code, but only in Pages where you want to disable:

ionViewDidEnter() {
  this.subscription = this.platform.backButton.subscribeWithPriority(9999, () => {
    // do nothing
  }
}

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

This disables the Backbutton on Page Enter and “enables” when you leave the Page.

1 Like

To extend on @EinfachHans’s excellent answer, don’t do anything relying on string names of classes or properties (this includes “page name”). Ever. You will find “solutions” that will work during testing and then break mysteriously in production.

this will work great help thanks.

1 Like