According to the documentation: https://ionicframework.com/docs/developing/hardware-back-button#exiting-the-app
For Angular would be (I’m using capacitor, but can use with Cordova as well):
import { IonRouterOutlet, Platform } from '@ionic/angular';
import { Plugins } from '@capacitor/core';
const { App } = Plugins;
constructor(
private platform: Platform,
private routerOutlet: IonRouterOutlet
) {
this.platform.backButton.subscribeWithPriority(-1, () => {
if (!this.routerOutlet.canGoBack()) {
//Chame a mensagem de confirmação customizada aqui, se confirmar execute App.exitApp();
}
});
}
React:
import { useIonRouter } from '@ionic/react';
import { Plugins } from '@capacitor/core';
const { App } = Plugins;
const ionRouter = useIonRouter();
document.addEventListener('ionBackButton', (ev) => {
ev.detail.register(-1, () => {
if (!ionRouter.canGoBack()) {
//Chame a mensagem de confirmação customizada aqui, se confirmar execute App.exitApp();
}
});
});
Vue:
import { useBackButton, useIonRouter } from '@ionic/vue';
import { Plugins } from '@capacitor/core';
const { App } = Plugins;
export default {
setup() {
const ionRouter = useIonRouter();
useBackButton(-1, () => {
if (!ionRouter.canGoBack()) {
//Chame a mensagem de confirmação customizada aqui, se confirmar execute App.exitApp();
}
});
}
}
Javascript:
import { BackButtonEvent } from '@ionic/core';
import { Plugins } from '@capacitor/core';
const { App } = Plugins;
const routerEl = document.querySelector('ion-router');
document.addEventListener('ionBackButton', (ev: BackButtonEvent) => {
ev.detail.register(-1, () => {
const path = window.location.pathname;
if (path === routerEl.root) {
//Chame a mensagem de confirmação customizada aqui, se confirmar execute App.exitApp();
}
});
});
Then you can use ion-Alert (it’s just a suggestion, you can do as you wish) to create a confirmation modal https://ionicframework.com/docs/api/alert, example in Angular:
async confirmarSairDoAplicativo() {
const alert = await this.alertController.create({
header: 'Sair do aplicativo!',
message: 'Deseja realmente fechar o aplicativo?',
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
handler: (blah) => {
console.log('Nada ocorre');
}
}, {
text: 'Okay',
cssClass: 'danger',
handler: () => {
App.exitApp();
}
}
]
});
await alert.present();
}