TransWikia.com

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

Stack Overflow Asked by outofworld on December 25, 2020

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

2 Answers

Try this,

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

Answered by pl-jay on December 25, 2020

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

Answered by Andran on December 25, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP