Reputation: 378
I have been playing with window.history.pushState and onpopstate but it seems to me that pressing back jumps back two states, skipping one.
See https://developer.mozilla.org/en-US/docs/Web/API/window.onpopstate?redirectlocale=en-US&redirectslug=DOM%2Fwindow.onpopstate for an example:
window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null
history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3}
History.js seems to display the same behaviour. See https://github.com/browserstate/history.js in the "Working with History.js directly" section. It jumps from state 3 to state 1 in the second back().
So why does it have this behaviour or am I missing something?
Upvotes: 0
Views: 2267
Reputation: 196187
That is because you use replaceState
for the third example.
replaceState
as the name implies replaces the current state.. it does not add a new one.
So after the history.replaceState({page: 3}, "title 3", "?page=3");
the ?page=2
one does not exist in the history...
Quoting the The replaceState() method
history.replaceState()
operates exactly likehistory.pushState()
except thatreplaceState()
modifies the current history entry instead of creating a new one.
Upvotes: 3