How to trigger change when using the back button with history.pushstate and popstate?

北战南征 提交于 2019-11-27 03:11:21
pimvdb

The popstate only contains a state when there is one.

When it goes like this:

  1. initial page loaded
  2. new page loaded, with state added via pushState
  3. 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();
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!