Browser Back Button does not trigger window.onbeforeunload
See original GitHub issueIn our application we have forms and want to prompt the user when they click the browser’s Back or Forward buttons to notify them they will lose their data if they continue.
- I have searched the issues of this repository and believe that this is not a duplicate.
Although it is similar in nature to this issue that has been marked as Exploration
Expected Behavior
When user clicks back button, window.onbeforeunload
function that is defined fires
Current Behavior
Browser redirects user to previous page without triggering window.onbeforeunload
action
Special Notes
If I navigate directly to the page with the form by typing in the url, clicking the Back button correctly triggers window.onbeforeunload
.
If I navigate away from the page with the form by typing in the url for another page, the window.onbeforeunload
event fires correctly.
If I navigate to the page using links within the application, clicking the Back button does not trigger window.onbeforeunload
.
I think this has something to do with they way the browser is treating our application when the user navigates within the application using Next Links. Instead of seeing each view as its own page and loading/unloading the page resources as the user navigates, it sees the entire application as just one page, thereby never loading/unloading resources and thus not triggering window.onbeforeunload
.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:14
- Comments:33 (6 by maintainers)
Top GitHub Comments
Thanks for that snippet @Fensterbank. Super useful.
I did notice one possible issue with it. Which I think is what prompted you to use the leaveConfirmed variable.
The function gets added as a listener to the event each time the component is rendered. So the page may end up creating hundreds of copies of that function, and calling each one of those copies when a user browses internally. And these never get cleared. Of course that might not be an issue in many use cases. But it was a problem with my particular scenario. Either way, I might suggest adding the router event listener in an event hook, just like the window
beforeunload
listener.Here is a version with this approach, for anyone who gets to this page looking for another solution. Note, I have adapted it a bit further for my requirements.
So far, it seems to work pretty reliably.
@Nitaaq Try this snippet that will work.