简体   繁体   中英

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM