1

I am trying to close a modal with the native Android back button in my project. The below code closes the modal but navigates back to the root of the project.

 document.addEventListener('backbutton', (event) => {
            if(modalIsOpen === true) {
                setIsOpen(false);
                event.preventDefault();
            } 
            else if(modalIsOpen === false && history.location.pathname === "/tabs/home"){
           App.exitApp();
            }
        });

My other solution was to use the capacitor App plugin

const ionRouter = useIonRouter();
     document.addEventListener('ionBackButton', (ev) => {
         ev.detail.register(-1, () => {
             if (modalIsOpen === true) {
                 setIsOpen(false);
                 event.preventDefault();
             }
             else if (modalIsOpen === false && !ionRouter.canGoBack()) {
                 App.exitApp();
             }
         });
     });

Neither work the way I desired them to work and really would love to figure this out! I also tried use history.push(); to push to the page the modal was close on to stop the navigation back to the root which worked but not for all pages.

Any help would be greatly appreciated.

Tomislav Stankovic
  • 3,080
  • 17
  • 35
  • 42
Ndango
  • 59
  • 8

1 Answers1

0

There could be other event listeners for the backbutton event. You might try using event capturing:

addEventListener('backbutton', () => { … }, { capture: true });

I’d also recommend moving the event.preventDefault() to the start of your callback.

Aaron Breckenridge
  • 1,723
  • 18
  • 25
  • still doesn't work even if I try the following code the modal close but the app still navigates back the the root. `document.addEventListener('backbutton', (event) => { event.preventDefault(); if (modalIsOpen === true) { setIsOpen(false); } }, { capture: true });` – Ndango Nov 18 '21 at 14:55