Skip to content

Instantly share code, notes, and snippets.

@forberg
Last active January 27, 2022 18:10
Show Gist options
  • Save forberg/183bc3e5cd3af3465e1830ff827443c0 to your computer and use it in GitHub Desktop.
Save forberg/183bc3e5cd3af3465e1830ff827443c0 to your computer and use it in GitHub Desktop.
Fix: Hack for iOS 15 history back scroll bug
(() => {
if (!navigator.userAgent.includes('iPhone OS')) {
return;
}
const STORE_KEY = '_ios_scroll_bug';
window.addEventListener('pagehide', () => {
sessionStorage.setItem(STORE_KEY, window.scrollY);
});
window.addEventListener('pageshow', (event) => {
if (!event.persisted) {
return;
}
const store = sessionStorage.getItem(STORE_KEY);
if (!store) {
return;
}
const storedScrollY = parseInt(store, 10);
if (storedScrollY && storedScrollY > window.scrollY) {
setTimeout(() => window.scrollTo(0, storedScrollY), 100);
}
});
})();
@eeue56
Copy link

eeue56 commented Jan 26, 2022

Maybe something like this would prevent the page looking jumpy?

(() => {
  if (!navigator.userAgent.includes('iPhone OS')) {
    return;
  }
  
  const STORE_KEY = '_ios_scroll_bug';
  
  window.addEventListener('pagehide', () => {
    sessionStorage.setItem(STORE_KEY, window.scrollY);
  });
  
  window.addEventListener('pageshow', (event) => {
    if (!event.persisted) {
      return;
    }
    document.body.style.visibility = "hidden";
    const store = sessionStorage.getItem(STORE_KEY);
    if (!store) {
      return;
    }
  
    const storedScrollY = parseInt(store, 10);
  
    if (storedScrollY && storedScrollY > window.scrollY) {
      setTimeout(() => {
        window.scrollTo(0, storedScrollY);
        document.body.style.visibility = "visible";
      }, 100);
    }

  });
})();

@olekenneth
Copy link

@eeue56 if the store (sessionStorage.getItem) fail you return without setting the body to visible again

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment