Search code examples
jquerylocal-storagebrowser-history

How can I get current (previous) URL state on statechange


So let's say I have a web app at

localhost:8080/myapp?home

If i change current state home to state1, I want to save the (previous) state home in local storage, like that

$.totalStorage("prevState", window.location.search.substr(1));

But where should this line be executed?

I am also using history.js library. But I can only get URL state after state is changed.

History.Adapter.bind(window, "statechange", function() {
    var page = window.location.search.substr(1); //page === "home"
});

I am also using this function

goTo : function(page) {
    var page = window.location.search.substr(1); //page === "state1", but not with back, forward, backspace buttons
    History.pushState({page: page}, getPageTitle(page), "?" + page);
}

But this only saves previous state when I change URL state with this function call. How can I do it globally, by pressing for example browser back and forward button and backspace or mouse back and forward buttons.


Solution

  • Why don't you create a history stack and add the current state to it? That gives you the opportunity to go back further than just one state. For example:

    $(window).on("statechange", function() {
        var historyStack = localStorage.getItem("stateHistory") === null ? [] : JSON.parse(localStorage.getItem("stateHistory"));
        historyStack.push(window.location.search.substr(1));
        localStorage.setItem("stateHistory", JSON.stringify(historyStack));
    });
    

    To navigate back you fetch the second last entry in the history stack and subsequently remove the last two(!) entries from the history stack before changing the state.