How to close a modal on back button click?

Is it possible to close a modal ( if open ), when the backbutton of the browser or phones back button is clicked.

Sorry not an answer to your question: but why do you want this? It doesn’t seem like a good user experience.

I expect my back button to take me to the previous page.

I expect a button inside the modal (X or ‘close’) to close the modal.

The only sites I know that hook into the back button are the scam sites that don’t want you to back out of their website.

Anyway here is some more reading if you want to try it: https://medium.com/cnk-tech/controlling-and-directing-browsers-back-button-with-javascript-eaa798acdeb5

I doubt there’s a premade wappler way to do this.

1 Like

@derick.007
If you are working with cordova, the code block below will work.
Also, it’s good to check out other events.
https://cordova.apache.org/docs/en/2.4.0/cordova/events/events.html#backbutton

function onBackKeyDown(e) {
  e.preventDefault();
}
document.addEventListener("backbutton", onBackKeyDown, false);

Use the popstate event.

Window: popstate event - Web APIs | MDN (mozilla.org)

The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in JavaScript).

This seems like a specific issue to Wappler SPA implementation. It’s my understanding this would be better solved directly at Wappler framework, what do you think?

In fact, this is not the first topic about the issue, I remember seeing the same issue for a regular Wappler Web app. I’m on mobile so I don’t have a link nearby to the topic in question

Edit:

This is something one naturally expects, as the issue doesn’t happen with non-SPA pages

I do not want to redirect to any page on back button click. When backbutton is clicked the opened modal should be closed and if no modal shown then it should be redirected.