Search code examples
javascriptpushstate

Javascript History can't retrieve value in onpopstate


Here's my code:

function pushState() {

    ...snip... (SelectedMenuID has a value of 8)

    var stateObj = { selectedMenu: SelectedMenuID };
    history.pushState(stateObj, "The title to use", path);
}

window.onpopstate = function(event) {
    if (event.state != null) {
        alert(event.state.selectedMenu);
    }
};

A couple of problems:

  • Clicking through on each page updates the navigation bar URL fine but does not update the title to the title to use as I expect it to
  • Pressing back it creates the alert but the value is undefined and not 8 as I would expect

Solution

    1. According to https://github.com/browserstate/history.js/wiki/The-State-of-the-HTML5-History-API there is no browser that currently updates the page title based on the value in pushState(). Personally I think this is the correct behavior - the page title should reflect the <title> element in the page head.

    2. When you call pushState() and then use the back-button you aren't going back to the last pushState (which is actually the current state) but to the state before that. In your case it sounds like you are seeing the state at page load which is why selectedMenu is undefined. By the way, it is only Chrome that fires onpopstate to match the initial page load, so in other browsers I wouldn't expect to see the alert.