6
votes

I'm using angular routing(@angular/router) for ionic 4 project to disable the device back-button in ionic 4 prevent-default is not working below is my code in

app.component.ts

    this.platform.backButton.subscribe(() => {
        if (this.router.url === '/Login') {
          this.util.presentAppExitAlert();
        } else {
          // event.preventDefault();
          console.log("invoing url ", this.router.url);
        }
      });
    });

i am not able to disable the device back-button any help here

7

7 Answers

13
votes
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();
    });
  }
4
votes

I found out how to undo it (give back button previous functionality):

Your observer is pushed to the this.platform.backButton.observers array. So you just have to pop the last element of the list:

this.platform.backButton.observers.pop();

Hope it helps somebody.

3
votes

05-02-2020

This works for me.

app.component.ts

  

async initializeApp(): Promise<void> {
    await this.platform.ready();
   
    this.platform.backButton.subscribeWithPriority(1, () => { // to disable hardware back button on whole app
    });

  }
0
votes

i found better way to do avoid back button device, and make disable back on whatever page do you want

import { Router, NavigationEnd } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class DisableBackService {
  // page disable back button
  private blackLists: string[] = ['/tab/wall', '/event-list', '/tutorial', '/offline-message'];

  constructor(private router: Router) {
    // call every have change page
    this.router.events.subscribe((ev) => {
      if (ev instanceof NavigationEnd) {
        const blackList = this.blackLists.find(el => ev.url.includes(el));
        if (blackList) {
          this.disableBack();
        } else {
          this.enableBack();
        }
      }
    });
  }

  private logger() {
    console.log('disable back button');
  }

  disableBack() {
    document.addEventListener('backbutton', this.logger, false);
  }

  enableBack() {
    document.removeEventListener('backbutton', this.logger, false);
  }
}
0
votes

It might be relevant to mention the use of capacitor to handle the back button which one will disable the default back button behaviour as described in the docs:

    /**
     * Listen for the hardware back button event (Android only). Listening for this event will disable the
     * default back button behaviour, so you might want to call `window.history.back()` manually.
     * If you want to close the app, call `App.exitApp()`.
     */
    addListener(eventName: 'backButton', listenerFunc: (data: AppUrlOpen) => void): PluginListenerHandle;

Usage:

import { Plugins, AppState } from '@capacitor/core';

const { App } = Plugins;

App.addListener('backButton', (data: AppUrlOpen) => {
  console.log('User pushed the back button, default behaviour has been overiden');
});

0
votes

You can achieve disable hardware back button for specific pages. Using below code in ionic 4.

 ionViewDidEnter() {
    this.backbutton = this.platform.backButton.observers.pop();
  }

  ionViewWillLeave() {
    this.platform.backButton.observers.push(this.backbutton);
  }
0
votes

disable hardware back button when using LoadingController in ionic 5. referred top two answers and merged them into loading controller code

import {
        LoadingController,
        Platform
    } from '@ionic/angular';
    constructor(public platform: Platform, private loadingController: LoadingController) {}

async presentLoading() {
    this.platform.backButton.subscribeWithPriority(10, () => {
        document.addEventListener('backbutton', () => {}, false);
    });
    const loading = await this.loadingController.create({
        spinner: 'circles',
        keyboardClose: true,
        message: 'Please Wait'
    }).then((res) => {

        res.onDidDismiss().then((d) => {
            this.platform.backButton.observers.pop();
        })
        return res.present()
    })
    return loading;
}