How can I ensure my Webflow website refreshes when users click the back button, while also keeping the scroll position intact?
TL;DR
- Use the
pageshowevent in your Webflow Footer Custom Code to detect back navigation via cache and triggerlocation.reload()whenevent.persistedis true. - If scroll position isn't retained after reload, store it in
sessionStorageon scroll and restore it on load usingwindow.scrollTo().
To refresh your Webflow site when users hit the back button while also preserving scroll position, you'll need to handle browser behavior manually, since browsers typically cache pages during back/forward navigation.
1. Understand Native Browser Behavior
- Browsers often restore the page from cache when users navigate with the back/forward buttons.
- They also retain the scroll position by default when the page is cached.
- Forcing a refresh can prevent stale data, but may cause the scroll position to be lost unless handled carefully.
2. Use the Pageshow Event to Detect Back Navigation
- Use the
pageshowevent withevent.persistedto detect if the page was restored from the cache. - This is supported in modern browsers and tells you when a bfcache (back-forward cache) restore occurs.
3. Add JavaScript to Reload on Back Navigation
- Use script inside your Webflow project’s Footer Custom Code section.
- Add the following code, which reloads the page only when it’s restored from cache:
- Go to Project Settings > Custom Code > Footer
- Paste this:
```
<script>
window.addEventListener('pageshow', function(event) {
if (event.persisted) {
location.reload();
}
});
</script>
```
- This forces the page to reload only when it's being restored from the back/forward cache — not on standard loads.
4. Preserve Scroll Position Manually (If Needed)
- In most cases, the browser will restore scroll position automatically after a reload from cache.
- If reloading via
location.reload()erases that, consider storing scroll position in sessionStorage:- On scroll:
sessionStorage.setItem('scrollY', window.scrollY) - On load:
window.scrollTo(0, sessionStorage.getItem('scrollY'))
- On scroll:
- Use this only if you find the scroll position is not retained after implementing the
pageshow-based refresh.
Summary
To refresh a Webflow page on back navigation while keeping the scroll position, use the pageshow event to detect cache restoration and trigger a reload. Browsers typically retain scroll position after such a reload, but sessionStorage can be used for added reliability if needed.