gmustudent
gmustudent

Reputation: 2199

Change URL Dynamically Without Adding Previous To History Stack

A stackoverflow question URL includes a servlet, id#, and title like so...

stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page

My webiste works the same way with URL's like so...

localhost:8443/user/1/admin

The query I do on the backend to get the users info only requires the id number. The name of the user after that is just for show. So if you typed this into the browser for localhost:8443/user/1/a it would give you the exact same page as this localhost:8443/user/1/admin

Stackoverflow is capable of noticing that the end part of the URL is missing and add it back. So if you put this into the address bar

stackoverflow.com/questions/824349/modify

They will change it to this dynamically

stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page

Now I did reading about changing URL's dynamically on stackoverflow and everyone kept referring to history.pushstate so I tried it. The problem with this is it adds the incorrect URL to the history stack. What I would like to accomplish is change the URL to the path it should be and not include the wrong URL to the history stack. So if the user decides to go back they go back to the actual page they were on last not, stackoverflow.com/questions/824349/modify. Just like stackoverflow does it. How could I do this!?

Upvotes: 4

Views: 3351

Answers (2)

tilleryj
tilleryj

Reputation: 14379

Try using history.replaceState instead of history.pushState

Upvotes: 1

JKS
JKS

Reputation: 3770

Check out the replaceState method.

Upvotes: 2

Related Questions