Prevent Android backbutton using Capacitor not working

  • Hello guys, if anyone can help me, I will be grateful.
    I am developing an application for Android with Quasar and Capacitor, and on a specific screen that will synchronize with the backend, I would like that when the user clicks the physical back button on the device, I can display an alert asking if he would really like stop syncing and exit.
    Using both the capacitor’s App plugin and the native event, they are triggered but do not prevent the return to the previous route. I am testing in a Samsung tablet SM-T290 with Android 10.

    import { Plugins } from "@capacitor/core";
    const { App } = Plugins;
    App.addListener('backButton', () => {
    document.addEventListener('backbutton', function(event) {
        console.log('Not work...');
     }, false);

  • @jonathan_on I use Vue lifecycle hook Vue-router navigation guard for this in Cordova, should work the same in capacitor.

  • @metalsadman Which hook do you use? I added the event both in created() and outside the default export, inside a deviceready listener. In both the log is displayed, but the screen is closed nonetheless.

  • @jonathan_on before destroy I believe, can’t check atm in mobile, but see Vue lifecycle hook diagram, it’s one of the befores iirc. also see this guide just checked now I meant vue router navigation guard beforeRouteLeave particularly

    I answered you this in discord: example of what I’ve done on a component that I pop up a dialog when user are leaving the current route (pressing back button, or clicking another route from the drawer).

    beforeRouteLeave (to, from, next) {
       // okToLeave is just a flag i've set somewhere in this component when a form field has changed etc..
        if (this.okToLeave) {
          // route accordingly
        } else {
            title: 'Leaving',
            message: 'Warning! Changes made in this page cannot be recovered. Are you sure you want to leave?',
            ok: {
              flat: true,
              color: 'warning'
            cancel: {
              color: 'secondary',
              flat: true
            persistent: true
          }).onOk(() => {
            // route accordingly
          }).onCancel(() => {
            // cancel route and stay in the same page.

Log in to reply