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:
the title to use
as I expect it toundefined
and not 8
as I would expectAccording 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.
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.