Skip to content

Instantly share code, notes, and snippets.

@jaredatron
Last active October 10, 2020 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredatron/171f471169e792c10d0979bd9522dd7a to your computer and use it in GitHub Desktop.
Save jaredatron/171f471169e792c10d0979bd9522dd7a to your computer and use it in GitHub Desktop.
How to track back and forward capability using history push state
/*
This is an example of how one could track if going back or forward is
an option for the user.
*/
if (!window.history.state || !window.history.state.visitedAt){
window.history.replaceState(
{...history.state, visitedAt: Date.now()},
window.document.title,
window.location,
)
}
function trackBackAndForwardState(){
let oldestVisitedAt = (
('oldestVisitedAt' in window.sessionStorage) &&
parseInt(window.sessionStorage.oldestVisitedAt, 10)
)
let latestVisitedAt = (
('latestVisitedAt' in window.sessionStorage) &&
parseInt(window.sessionStorage.latestVisitedAt, 10)
)
const visitedAt = window.history.state && window.history.state.visitedAt
if (!visitedAt){
console.warn('visitedAt is missing')
return {canGoForward: true, canGoBack: true}
}
if (!latestVisitedAt || visitedAt >= latestVisitedAt)
window.sessionStorage.latestVisitedAt = latestVisitedAt = visitedAt
if (!oldestVisitedAt)
window.sessionStorage.oldestVisitedAt = oldestVisitedAt = visitedAt
return {
canGoForward: visitedAt < latestVisitedAt,
canGoBack: window.history.length > 1 && visitedAt > oldestVisitedAt,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment