I want to update the URL using window.location.hash
or history.pushState
.
What are the differences and advantages of each method?
In an HTML document, the history. pushState() method adds an entry to the browser's session history stack.
The big difference is, that while pushState will create a new entry in the browser's history, replaceState will only replace the current state. As a side effect of this, using the replaceState method will change the URL in the address bar, without creating a new history entry.
API Overview The pushState() method enables mapping of a state object to a URL. The address bar is updated to match the specified URL without actually loading the page.
The history. pushState() method allows you to add an entry to the web browser's session history stack. Here's the syntax of the pushState() method: history.pushState(state, title, [,url])
location.hash
has a better support than the history.pushState
method.
The advantage of the pushState
method is that you can bind a state to the history entry.
If you don't need this state object, I recommend to use the location.hash
property, to have better compatibility with older browsers.
location.hash = 'new-hash'; console.log(history.state); // null or undefined history.pushState({extraData: "some state info"}, '', 'new-hash'); //<--- console.log(history.state); // [object Object] = {"extraData": "some state info"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With