Search code examples
androidangularionic-frameworkcapacitorionic5

Ionic 5 Capacitor hardware back button ending the app


I have a problem testing my ionic app on my phone and android studio, when i press the hardware back button the application inmediatly exits, i've tried many solutions, but it simply won't work and won't listen to whatever i code into it.

Here is my attempt

import { Component, Renderer2, ViewChild } from '@angular/core';

import { IonRouterOutlet, Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { TranslateService } from '@ngx-translate/core';
import { Location } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {

  @ViewChild(IonRouterOutlet, {static: true}) routerOutlet: IonRouterOutlet
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private renderer: Renderer2,
    private translate: TranslateService,
    private location: Location
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.translate.setDefaultLang( localStorage.getItem('default-language') ? localStorage.getItem('default-language') : navigator.language.slice(0, 2) )
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.backButtonEvent();
      if (localStorage.getItem('color-theme')) {
        this.renderer.setAttribute(document.body, 'color-theme', localStorage.getItem('color-theme'))
      } else {
        if(window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches === true) 
          this.renderer.setAttribute(document.body, 'color-theme', 'light')
        else
          this.renderer.setAttribute(document.body, 'color-theme', 'dark')
      }
    });
  }

  backButtonEvent() {
    this.platform.backButton.subscribeWithPriority(0, async () => {
      if(!this.routerOutlet.canGoBack())
        navigator["app"].exitApp()
      else
        this.location.back()
    });
  }


}


Solution

  • Try it this way using the @capacitor/app package:

    import { App } from '@capacitor/app';
    
    App.addListener('backButton', ({ canGoBack }) => {
      if(canGoBack){
        window.history.back();
      } else {
        App.exitApp();
      }
    });