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', () => {
        console.log('Blocked');
    });
    
    document.addEventListener('backbutton', function(event) {
        event.preventDefault();
        event.stopPropagation();
        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 https://quasar.dev/vue-directives/go-back#Introduction. just checked now I meant vue router navigation guard beforeRouteLeave particularly https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards.

    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
          next()
        } else {
          this.$q.dialog({
            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
            next()
          }).onCancel(() => {
            // cancel route and stay in the same page.
            next(false)
          })
        }
      }
    

Log in to reply