TL;DR
In a multipage application, pressing the back button should restore the scrolling position of the previous page so that the user ...
For further actions, you may consider blocking this person and/or reporting abuse
This is a really great idea (this solves a frustrating UI/UX issue with many React sites that I encounter as a user, and workarounds with back buttons on sites that bypass the browser are just bad), but this creates an issue with newer versions of Chrome that will not allow you to read the global ("Window") "localStorage" prop. Depending on user settings, it will give you an error and the script will die.
Hmmm, yeah I just noticed that looking at incognito mode. I'll update it so it at least doesn't die! Thanks...
EDIT: Script now fixed. If there is no access to sessionStorage then scrolls will not be reloaded in a MPA. It will continue to work in a SPA.
@miketalbot @bbutlerfrog do you guys know if it'll also lock acces to indexedDB?
Because if the answer is NO then we might have an universal solution there, or even use a Cookie to store the position 😅 i know bad practices, you'll send that on every request to the server yada yada...
I've had a look about and it looks like it is restricted. I guess it would be possible to attempt to encode it on the URL...
Yeah! I usually don't like to "pollute" the URL unless it's extremely necessary but... That might be the best idea then, the feature is probably great enough in several scenarios to justify it
I'll give it a go and post a follow up.
Ok that's done and this article and the Code Sandbox are updated with a version that will encode to the URL if it finds it can't access session storage.
That's amazing thanks! 🤩
Here's a TypeScript version if you prefer:
I wonder if you could use the history API? In addition to the URL you can give the location a data payload, which is available even when accessed by the back button. I don’t know if that is locked in privacy mode though
The answer was yes, and it's much neater!!! Great call. Will probably write it up as a second article exploring some of the concepts. Here it is:
Well we don't need it while the page is open, but its certainly possible it could survive a page navigation in an MPA. The url version survives well, but it would be neater.