How to capture the backbutton event on a PWA (Ionic5/Angular11/Capacitor) site by clicking the back button of an Android phone

Asked

Viewed 7 times

0

I used the following code:

       import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
       import { Location } from '@angular/common';    
       import { Platform, AlertController, IonRouterOutlet } from '@ionic/angular';  
       import { AppUrlOpen, Plugins } from '@capacitor/core';

      
       const { App } = Plugins;  

       @Component({
         selector: 'app-root',
         templateUrl: 'app.component.html',
         styleUrls: ['app.component.scss']
       })
       export class AppComponent implements OnInit, OnDestroy {
          @ViewChild(IonRouterOutlet, { static: true }) routerOutlet: IonRouterOutlet;

       ...

       constructor(
           private platform: Platform,
           private _location: Location,
           private alertCtrl: AlertController,
       ) 
       {
           this.initializeApp();
       }

      initializeApp() {
       this.platform.ready().then(() => {
    
          this.platform.backButton.subscribeWithPriority(10, () => {
            if (!this.routerOutlet.canGoBack()) {
              this.showExitConfirm();
            }
            else {
              this._location.back();
            }
          });
        });
      }

     showExitConfirm() {
        this.alertCtrl.create({
            header: 'App termination',
            message: 'Do you want to close the app?',
            backdropDismiss: false,
            buttons: [{
               text: 'Stay',
               role: 'cancel',
            handler: () => {
               console.log('Application exit prevented!');
            }
          }, {
          text: 'Exit',
          handler: () => {
             //navigator['app'].exitApp();
             App.exitApp();
          }
        }]
       })
       .then(alert => {
         alert.present();
       });
    } 
   }

The app is published in the cloud and accessed by mobile as a PWA. I can not in any way capture the backbutton event (by clicking the back button of Android) to show the alert.

Question: is it a limitation of Ionic ? Can it work ?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.