2

I am working on a PWA and I have a page with a full screen modal in it, which pops up upon a button click to perform a specific action.

On the modal I have a close button tied to a function which works fine in closing the modal. However I noticed that on most native apps, when a modal is active clicking the (android) back button in a UI like mine closes the modal instead of going to the previous view.

My concern is if it were possible to listen to the android back button being clicked, prevent the default action and call another action. Or if there's anyway else around this!

I've made researches but all I can see is handling the browser back button, which in my case does not work. Tested on samsung A30,S10,A50.

From the Suggested question which I had gone through, There's no answer concerning how to handle the back button, Only on how to intercept it. And none of those answers my question.

Kindly note, PWA is already installed, hence in standalone mode

Emmanuel
  • 407
  • 3
  • 13

1 Answers1

3

There is no way to handle the back button of Android in the PWA environment.
It is a system button which "clicks" the history.back() of an open browser. If there is no back-history it closes the browser.
But it doesn't know anything about this special button. There would be the need for something like the keypress-events. But there is no standard and so no implementation in the browsers.

The only way to handle this stuff in your app, is to manage the history.state in your app. Push a new state with opening the modal. And close the modal in the popstate-event.

https://developer.mozilla.org/en-US/docs/Web/API/History_API/Working_with_the_History_API

Markus
  • 512
  • 1
  • 4
  • 21
  • Yeah I realized thus, I currently use the history_state to manage navigations, tried working my way around using it for the modal, didn't turn out well! It works on some occasions if the user visits that page as the first page on that session, however if the user visits another page and navigates to that page as !1 when the back key is pushed it returns to the previous page. I have seen situations where this works well in react, If building a SPA, still haven't figured it out since our app is not a SPA. – Emmanuel Oct 29 '19 at 09:59