-
-
Save ASDAFF/9132a3c7ca75d20625e76597d6c0ad8f 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