What is the use of window.history.replaceState?

1

Hello, I would like to know what the following code does:

window.history.replaceState  
    
asked by anonymous 23.06.2015 / 18:24

1 answer

2

Methods and history .replaceState () were introduced in HTML5 to be able to retrieve and modify values during the user's browsing history.

Both methods work in the same way, the only difference is that pushState adds a new state in history while replaceState overrides the state that was put by pushState .

Both have three parameters: state object , title and URL .

  • state object - This 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 retrieve this object through the event called popstate . In addition 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 that URL is just visual.

Example:

  • Create a test.html file

  • Add the following code to it and open it in your 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 browser back and next to realize the alerts .


    One important thing!

    If you want to be transitioning objects through history states that are VERY large, it is recommended to use sessionStorage or localStorage .

    >


    Want to play more with pushState and replaceState ?

    link

    It's a great example of how to work with these methods.


    Sources:

    23.06.2015 / 19:18