Javascript history state incorrect

Rohit Banga picture Rohit Banga · Oct 28, 2012 · Viewed 8.2k times · Source

I am trying to populate the index of the currently selected tab using

history.pushState({tabSelected: 1}, null, "");

I have a handler to the popstate event in jquery which programmatically switches the jquery ui tabs.

 $(window).bind("popstate", function(event) {
                               var state = event.originalEvent.state;
                               ...
                            }

This works fine and the browser and I am able to switch between tabs using back and forward buttons. Also works with two layers of tabs.

But in certain cases I want to push additional state to the stack. So I do the following:

 var content = { targetId : id,
                  targetContent : $("#myDivId").html()
               };
 $.extend(content, {tabSelected: currentTab});
 history.pushState(content, null, "");

content looks good before and after I push it on the history. Checked with console.log(history.state); Also tried checking in chrome console.

But in my popstate handler I am not seeing the targetId, tabSelected attributes on the object event.originalEvent.state. I am seeing the correct value of tabSelected on the object but for some reason I am seeing a trimmed down state.

Checked in both Chrome and Firefox. Cannot get the correct content. Any ideas what could be wrong? Thanks in advance.

Update

Also tried incrementing a global variable on every pushstate and adding it to the state. It turns out that for the particular case I am mentioning the global variable goes to a value 48 instead of 49 implying it is picking up the last but one event. I don't see my popstate handler being invoked in between. No idea what is going on.

Another Update

When I call history.pushState(content, null, "") twice it works fine. (only in one place, at the other place I am still calling it once). It looks like for some reason the browser is returning the last but one state. Apparently there is something wrong with my code as this workaround works in both chrome and firefox.

Answer