If you are utilizing views to display your entire page, it may be challenging to find a simple solution for browser scrolling on the back button.
When using templates in HTML/CSS/JavaScript, you have two options: either rely entirely on the browser to handle scrolling (which works when the page is cached by the browser) or implement a script that saves previous and current routes in local storage and checks scrolling upon page load:
const storedRoutes = localStorage.getItem("routes");
const currentPath = window.location.pathname;
let newPreviousRoute = null;
if(storedRoutes) {
const routes = JSON.parse(storedRoutes);
const isPreviousRoute = routes.previous != null
&& routes.previous.path === currentPath;
if(isPreviousRoute){
const { x, y } = routes.previous;
window.scrollTo(x,y);
}
newPreviousRoute = routes.current;
}
const newRoutes = {
current: { x: 0, y: 0, path: currentPath },
previous: newPreviousRoute
}
localStorage.setItem("routes", JSON.stringify(newRoutes));
Include this script on the load of each page.
Additionally, add a listener on beforeunload to capture the last scroll position:
const xScroll = window.pageXOffset
?? document.documentElement.scrollLeft
?? document.body.scrollLeft
?? 0;
const yScroll = window.pageYOffset
?? document.documentElement.scrollTop
?? document.body.scrollTop
?? 0;
let updatedRoutes = JSON.parse(localStorage.getItem("routes"));
updatedRoutes = { ...updatedRoutes, current: { ...updatedRoutes.current, x: xScroll, y: yScroll } };
localStorage.setItem("routes", JSON.stringify(updatedRoutes));
Keep in mind that this method will enforce scrolling even when a link on your page redirects to the previous one.
Addition: If you're considering using a frontend framework like Vue with Vue Router, you can simplify this process by utilizing <router-link>
for navigation within your website, as scrolling will be handled automatically. Check out this feature in the documentation. A similar approach is used by Twitter, as seen here where they employ React Native for web.