Confirm if user wants to leave page

Hi,

I was wondering what is the best method to create a custom prompt to ask the user if they are sure they want to leave the page.
Preferably I would like this confirmation to trigger if they hit the back button, attempt to close the tab, or attempt to navigate to a different page (unless the form on the page is submitted).

I’ve gotten success using window.onbeforeunload in a tag, however the ability for a custom message appears to be long gone for most browsers, and the generic message given by this is not ideal for this situation.

Apologies if this question has been asked before on these forums, I couldn’t seem to find anything through searching, If anyone can point me in the right direction it would be appreciated!

There are ways to hack the “back” event, but there is no way to capture tab/window close event in a manner other than the generic message from what I know.

Hi Sid,

Thanks for the quick reply!
I think not being able to handle the tab being closed should be fine, its mainly being able to handle the “back” event and other navigations that is the main sticking point.
Do you have any information regarding that?

Many Thanks

Answers here should be of some help.
The events for hashchange and pophistory should help you capture the navigation you want.

Although, you must understand that Wappler does not have any of this built in. This is completely custom JS script.

Thank you!

I’ll have a look at that ASAP.

I need the same thing. When a user if filling in a form and either accidentally or intentionally navigate away they need to be presented with a warning asking if they want to SAVE their work or DISCARD/ABANDON their work.

A bit like this…

image

From my point of view it’s stopping them from accidentally navigating away using the Nav Bar or other link that might be on the page such as in the footer.

EDIT
Thinking more about this I have come to realise that it’s not just about leaving the page because in my instance I need some sort of warning within an SPA. I am therefore not necessarily going to another page, I am actually navigating to another SPA page.
So, I need some sort of event listener to flag if any field within the form has changed and base the warning on that flag.
Hmmm… can someone help me on this?

The link I have shared above should take care of navigation changes - all SPA page changes are also under this category.
I have used the history event before in a Wappler SPA project, and it seems to work fine.
Although, I was just using this to change the UI, and not to prevent it from happenning, so you might have to do some more research on that.

Seen this one @UKRiggers?