Skip to content

Instantly share code, notes, and snippets.

@kottenator
Created October 26, 2016 18:56
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 kottenator/966242a6c31c3c99a11e9ebb139ba658 to your computer and use it in GitHub Desktop.
Save kottenator/966242a6c31c3c99a11e9ebb139ba658 to your computer and use it in GitHub Desktop.
Document title & History API
var button = document.createElement('button');
button.textContent = 'Push';
document.body.appendChild(button);
var x, title;
if (!history.state) {
x = 0;
title = document.title;
// Without this we can loose the initial page's title on browser navigation
history.replaceState({x: x, title: title}, title, location.href);
} else {
x = history.state.x;
}
button.addEventListener('click', function() {
x++;
title = 'Page ' + x;
history.pushState({x: x, title: title}, title, 'page-' + x);
// Without this we'll loose titles on push state
document.title = title;
});
window.addEventListener('popstate', function(e) {
if (e.state) {
// Without this - we'll loose titles on browser navigation
document.title = e.state.title;
x = e.state.x;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment