Skip to content

Instantly share code, notes, and snippets.

@Isa3v
Created July 31, 2020 12:14
Show Gist options
  • Save Isa3v/72030476b33bfc647d32b4c879f92176 to your computer and use it in GitHub Desktop.
Save Isa3v/72030476b33bfc647d32b4c879f92176 to your computer and use it in GitHub Desktop.
Возврат к позиции на странице при нажатии “Назад” (History API)
var isDeviceIos = navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i);
var historyScrollBack = (historyTab) => {
if (history.state && historyTab.hasOwnProperty('lastScroll')) {
window.scrollTo(0, historyTab.lastScroll);
}
};
// Возрват к позиции при нажатии кнопки назад (Запись)
window.addEventListener((isDeviceIos ? "pagehide" : "beforeunload"), function (e) {
if(window.history && history.pushState && history.state !== undefined){
history.pushState({ 'lastScroll': window.pageYOffset }, 'lastScrollEvent');
}
});
// Если есть запись о последнем положении, то переходим к позиции
document.addEventListener('DOMContentLoaded', function () {
if (window.history && history.pushState && history.state !== undefined) {
window.history.scrollRestoration = 'manual';
historyScrollBack(history.state);
}
});
// Safari back
window.addEventListener('popstate', function (event) {
historyScrollBack(event.state);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment