How to trigger change when using the back button with history.pushstate and popstate?
The popstate
only contains a state when there is one.
When it goes like this:
- initial page loaded
- new page loaded, with state added via
pushState
- back button pressed
then there is no state, because the initial page was loaded regularly, not with pushState
. As a result, the onpopstate
event is fired with a state
of null
. So when it is null
, it means the original page should be loaded.
You could implement it such that history.pushState
will be called consistently and you only need to provide a state change function like this: Click here for jsFiddle link
function change(state) { if(state === null) { // initial page $("div").text("Original"); } else { // page added with pushState $("div").text(state.url); }}$(window).on("popstate", function(e) { change(e.originalEvent.state);});$("a").click(function(e) { e.preventDefault(); history.pushState({ url: "/page2" }, "/page2", "page 2");});(function(original) { // overwrite history.pushState so that it also calls // the change function when called history.pushState = function(state) { change(state); return original.apply(this, arguments); };})(history.pushState);
Maybe it's not best solution, and maybe it doesn't suit your needs. But for me it was best to just reload the page. So the page is consistent an it loads everything according to current querystring.
$(document).ready(function() { $(window).on("popstate", function (e) { location.reload(); });});