Javascript history state incorrect

别来无恙 提交于 2019-12-23 09:02:13

问题


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.

来源:https://stackoverflow.com/questions/13107147/javascript-history-state-incorrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!