Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

JavaScript pushState does not work on browser going back

The concerning site-url is example.com/news/. The page that is loaded via this url contains some checkboxes and a button. I use an object filter with some keys like checkbox1, checkbox2, etc. and if the checkboxes are checked the keys get a true-value, if they are unchecked the keys get a false-value.

In the end, there is a var overwriteURL, which contains let's say the value "general-seniors-youth".

Now when the button is clicked, I want the script to load a page into a container and change the url to example.com/news/general-seniors-youth/ without loading a new site. I achieve this by the following code:

if(overwriteURL !== "" ) {
   history.pushState({ test: "test" }, null, "/news/" + overwriteURL + "/");
}

That works fine. As the documentation of Mozilla (https://developer.mozilla.org/de/docs/Web/Guide/DOM/Manipulating_the_browser_history) says in English: If I navigate to google.com (for example) after the script ran and then use the back-button of my browser, the URL-bar should actually contain the changed URL, so example.com/news/general-seniors-youth/. But it does contain the orginal URL before the pushState, so example.com/news/. But when I don't navigate to google.com but use the back-button as often as I want and then the forward-button till it reaches the latest history-entry, then the rigth (changed) URLis displayed in the URL-bar.

Where's the mistake?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, I don't know how, but I found a solution.

I figured that, the problem seems to be depending on the content of the var overwriteURL. On the real site, the var sometimes consists of a mixture of characters and numbers and the -- to seperate the values (for example: -general--seniors--u19--u16--press-).

When I experimented with the content of the var overwriteURL, sometimes there was no problem. So finally I replaced the -- by / and now it works perfectly. The new var overwriteURL for example looks like general/seniors/u19/u16/press/.

So, as a conclusion, it seems as if there is a problem with to many - in the URL.

Case closed!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...