The HTML5 history spec is quirky.
history.pushState()
doesn't dispatch a popstate
event or load a new page by itself. It was only meant to push state into history. This is an "undo" feature for single page applications. You have to manually dispatch a popstate
event or use history.go()
to navigate to the new state. The idea is that a router can listen to popstate
events and do the navigation for you.
Some things to note:
history.pushState()
and history.replaceState()
don't dispatch popstate
events.history.back()
, history.forward()
, and the browser's back and forward buttons do dispatch popstate
events.history.go()
and history.go(0)
do a full page reload and don't dispatch popstate
events.history.go(-1)
(back 1 page) and history.go(1)
(forward 1 page) do dispatch popstate
events.You can use the history API like this to push a new state AND dispatch a popstate event.
history.pushState({message:'New State!'}, 'New Title', '/link');
window.dispatchEvent(new PopStateEvent('popstate', {
bubbles: false,
cancelable: false,
state: history.state
}));
Then listen for popstate
events with a router.