title: Safari browser back button on mobile, doesn't return user to last scroll position on previous page
body: <p>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.</p>
  <p><strong>What Should Happen:</strong></p>
  <p>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.</p>
  <p><strong>Problem:</strong></p>
  <p>When testing on Safari on an iPhone, the user is always returned to the top of the webpage, not their last scroll position.</p>
  <p>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?</p>
  <p><strong>Code</strong>:
  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.</p>
  <p>I'm not sure if maybe popstate is fired differently on mobile or maybe localStorage isn't saved when the webpage is exited.</p>
  <pre><code>$(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(&quot;scroll&quot;, $(document).scrollTop());
   });
  
  
  </code></pre>