Created
July 31, 2020 12:14
-
-
Save Isa3v/72030476b33bfc647d32b4c879f92176 to your computer and use it in GitHub Desktop.
Возврат к позиции на странице при нажатии “Назад” (History API)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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