Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page does not get reloaded when going back in history in combination with window.history.pushState

When I change the url with window.history.pushState the page is not automatically reloaded when going back in history of the browser, e.g. by clicking on the "history-back-button". Why is the page not automatically reloaded? Can I change this behavior?

Here is a little piece of code to exemplify this "problem":

<html>
    <head>
        <title>Location test</title>
        <script>
            function load() {
                var value = window.location.search.substr(1);
                document.getElementById('myInput').value = value;
                document.title = 'Location test - ' + value;
            }
            function set(el) {
                window.history.pushState('', '', window.location.pathname + '?' + el.value);
                document.title = 'Location test - ' + el.value;
            }
        </script>
    </head>
    <body onload="load();">
        <input id="myInput" type="text" onkeyup="set(this);">
    </body>
</html>

Just write something into the text-field and the browser-history is updated accordingly. Click on the browser's history back button does not refresh the page. You have to manually refresh it.

I have worked around this by inserting my own "back-button" on the website which runs window.history.back(); location.reload();. But I would be happy if the normal browser "history-back-button" did the trick (as well).

like image 638
Daniel Avatar asked May 02 '14 13:05

Daniel


1 Answers

I think this may explain the topic much better than me. http://rosspenman.com/pushstate-jquery

popstate is the key

I'm working on a very similar problem. Don't think its pretty but the following snippet or a variation thereof may help

    $(window).on("popstate", function(e) {
        if (e.originalEvent.state !== null) {
        location.reload()
        }
    });
like image 178
Craig.C Avatar answered Sep 24 '22 13:09

Craig.C