I am trying to make my webpage return the user to their last scroll position of the previous page when they click the browser back button.
What Should Happen:
The user clicks a link on the page which directs them to a different site, then when they click the browser back button they should return to the previous page at the last scroll position. This works correctly on Chrome and Safari on macOS automatically with no code needed.
Problem:
When testing on Safari on an iPhone, the user is always returned to the top of the webpage, not their last scroll position.
Are there any know reasons as to why Safari on mobile returns to the top of the previous page when the browser back button is clicked?
Code: The below code attempts to save the last scroll position in localStorage and then scroll to that position when popState is triggered. PopState is used because other triggers like load seem to not work when the back button is clicked on Safari. With these considerations it still does not work.
I'm not sure if maybe popstate is fired differently on mobile or maybe localStorage isn't saved when the webpage is exited.
$(window).on('popstate', function(event) {
var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
if(is_safari){
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
var scroll = window.localStorage.getItem('scroll');
if (scroll !== null) $(document).scrollTop( scroll );
}
});
$(window).on('scroll', function() {
window.localStorage.setItem("scroll", $(document).scrollTop());
});