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);
1 Like

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).

1 Like

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

1 Like

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.

1 Like

This is also what Iā€™m fighting in my SPA, Iā€™ve had no real luck except moving all my modals to a layout page and calling all the actions from that, it at least prevents the greyed out unclickableness you get if someone hits back when theyā€™ve opened a modal.

Thanks this was the solution I was looking for