Home > Software engineering >  How to keep the state using history.replaceState?
How to keep the state using history.replaceState?

Time:01-25

I try to use the window.history.replaceState method just to show the URL shown in the browser.

window.history.replaceState("","","newurl.php");

Well, this works well and changes the URL. But what is this "State" that I set to "" here? And how should I change my code if I simply want to be the State as before? (As I said... I just wanted to change the URL and this works well, not to change the state...)

CodePudding user response:

.replaceState() a way to associate some data (any data that can be structured cloned) with the current location - without reloading the page. There's also pushState, that does the same thing, but you can also use the browser's back button to go back to the previous displayed url / state.

If you don't use these for something else, you don't have to care about the state you set (it's only visible to your website).

If you, on the other hand, do use states, and don't want to change it, you can set the same state as it was before. You can get the current state with history.state:

window.history.replaceState(window.history.state,"","newurl.php");
  •  Tags:  
  • Related