outofworld
outofworld

Reputation: 384

Ionic-5 app is closing instead back to previous page on click of hardware back button

I am using angular 7 and ionic 5. When i want to redirect to previous page using hardware back button, ionic app is closing itself. I am using below code but its not working.

 this.platform.backButton.subscribeWithPriority(9999, () => {
        document.addEventListener('backbutton', function (event) {
          event.preventDefault();
          event.stopPropagation();
          console.log('hello');
        }, false);
      });

Upvotes: 3

Views: 3396

Answers (3)

RafaelJan
RafaelJan

Reputation: 3606

If you are using ionic with Capacitor you need to use this code in the constructor of app.component.ts:

import { App } from '@capacitor/app';
import { Location } from '@angular/common';

constructor(private _location: Location)
{
  App.addListener('backButton', () =>
  {
    if (this._location.isCurrentPathEqualTo('/home'))
    {
      navigator['app'].exitApp();
    } 
    else
    {
      this._location.back();
    }
  });
}

Upvotes: 2

pl-jay
pl-jay

Reputation: 1100

Try this,

 this.platform.backButton.subscribeWithPriority(10, () => {
      this.router.navigate(['']); // route to previous page or component
 });

Upvotes: 0

Andran
Andran

Reputation: 299

I use the directive for this

import { Directive, HostListener } from '@angular/core';
import { PlatformService } from 'src/app/services/platform';

@Directive({
    selector: '[disableBackButton]'
})
export class DisableBackButtonDirective {

    constructor(
        private platformService: PlatformService
    ) { }

    @HostListener('document:ionBackButton', ['$event'])
    overrideHardwareBackAction(event: any) {
        if (this.platformService.isPlatform('android')) {
            event.detail.register(100, async () => {
                event.stopImmediatePropagation();
                event.stopPropagation();
                event.preventDefault();
            });
        }
    }
}

in page.html

<ion-content disableBackButton>
    ....
</ion-content>

in page.ts

this.platform.backButton.subscribe(() => {
    console.log('hello');
});

Upvotes: 0

Related Questions