2
Hi, I’d like to know what the following code does:
window.history.replaceState
2
Hi, I’d like to know what the following code does:
window.history.replaceState
4
The methods history.pushState() and history replaceState() were introduced in the HTML5 to be able to recover and modify values during user’s browsing history.
Both methods work the same way, the only difference is that the pushState
adds a new status to the history while the replaceState
overrides the state that was placed by pushState
.
The two have three parameters: state Object, title and URL.
state Object - It is the object that will be associated with that particular history created by pushState()
. When the user uses the back button in the browser or by history.go(-1)
it is possible to recover this object through the event called popstate
. Beyond the object needs to be serializable.
title - is an optional title, ignored so far.
URL - modifies the URL
that appears in the browser, but does not really redirect to this URL
is just visual.
Create a test.html file
Add the following code from it and open it in the browser.
<script>
window.onpopstate = function(event) {
alert("url: " + document.location + ", objeto: " + JSON.stringify(event.state));
};
// cria o primeiro estado no histórico
history.pushState({pagina: 1}, "titulo 1", "?pagina=1");
// cria o segundo estado no histórico
history.pushState({pagina: 2}, "titulo 2", "?pagina=2");
// sobrescreve o estado atual (2) por um novo
history.replaceState({pagina: 3}, "titulo 3", "?pagina=3");
// volta uma pagina, você estava no (3) volta pro (1), pois o (2) foi sobrescrito
history.back(); // alerts "url: .../exemplo.html?pagina=1, objeto: {"pagina":1}"
// volta pra primeira pagina onde não tinha nenhum estado criado ainda, pois você já volto uma e esta no (1)
history.back(); // alerts "url: .../exemplo.html, objeto: null
// avança 2 páginas, estava no "null", passou pelo (1) e voltou pro (3)
history.go(2); // alerts "url: .../exemplo.html?pagina=3, state: {"pagina":3}
</script>
Stay using the come back and move forward of the browser to understand the Alerts.
If you want to keep moving objects through the states of history that are VERY MUCH large, it is recommended to use sessionStorage or localStorage.
pushState
and replaceState
?http://blogs.sitepointstatic.com/examples/tech/history-pushstate/index.html
It’s a great example of how to work with these methods.
Browser other questions tagged javascript html html5-history
You are not signed in. Login or sign up in order to post.
Nothing, it’s commented. RA! I think you should read the documentation champz : https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_replacestate()_method
– Edgar Muniz Berlinck
http://www.igorescobar.com/blog/2012/05/05/mudando-a-barra-de-endereco-do-browser-sem-refresh/
– Gabriel Rodrigues