6

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

Sampath
  • 63,341
  • 64
  • 307
  • 441
Mohan Gopi
  • 7,606
  • 17
  • 66
  • 117

7 Answers7

14
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();
    });
  }
Davide Martina
  • 186
  • 2
  • 7
  • Working for me i'm using ionic 4.1 this code have to go in the app-component.ts and import in the platform :) – Davide Martina Mar 21 '19 at 12:03
  • is it possible to add it when loading is present and enable when loading end ? – Rakesh Roy Jul 13 '19 at 07:12
  • and how to remove it? – manish kumar Aug 01 '19 at 18:38
  • How can I adjust this code to make the back button cause a navigate back to login screen? I tried adding this.router.navigate(['/login']) after your 'hello' line, but get the error: Cannot read property 'navigate' of undefined. I have added private router: Router to the constructor, but still same error. – lepton Oct 23 '19 at 16:57
  • Your code works but is technically wrong, you are adding an event listener every time someone push on the back button. The trick to prevent the 'backbutton' propagation is however [not that wrong](https://stackoverflow.com/a/46986927/532695) despite we wish to have had a `document.removeAllEventListener('backbutton')` which does not exists. – Flavien Volken Jul 28 '20 at 09:33
  • This way you are subscribing to the `backbutton` event EVERYTIME the back button is pressed. – Mahmood Dehghan Nov 04 '21 at 14:05
7

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.

elnezah
  • 425
  • 5
  • 17
5

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
    });

  }
Sampath
  • 63,341
  • 64
  • 307
  • 441
1

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);
  }
Ravi
  • 51
  • 4
0

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

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');
});

Flavien Volken
  • 19,196
  • 12
  • 100
  • 133
0

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;
}