Skip to content

Instantly share code, notes, and snippets.

@snellingio
Created November 30, 2022 15:00
Show Gist options
  • Save snellingio/de92f6b8e12ea36b30d66812d0ddfadb to your computer and use it in GitHub Desktop.
Save snellingio/de92f6b8e12ea36b30d66812d0ddfadb to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="module">
customElements.define('history-component', class extends HTMLElement {
connectedCallback() {
// get the history from localstorage, if it exists
// if the current route is the latest, do not add it to the history
// if the current route is not the latest, add it to the history
// if the history is longer than 5, remove the oldest
// save the history to localstorage
// render the history
let history = JSON.parse(localStorage.getItem('history')) ?? []
let currentRoute = window.location.pathname
let latestRoute = history[history.length - 1]
if (currentRoute !== latestRoute) {
history.push(currentRoute)
}
if (history.length > 5) {
history.shift()
}
localStorage.setItem('history', JSON.stringify(history))
this.innerHTML = history.reverse().map(i => `<a href="${i}">${i}</a>`).join('<br>')
}
})
</script>
</head>
<body>
<history-component></history-component>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment