【问题标题】:Page does not get reloaded when going back in history in combination with window.history.pushState结合 window.history.pushState 返回历史时页面不会重新加载
【发布时间】:2014-05-02 13:49:36
【问题描述】:

当我使用window.history.pushState 更改网址时,返回浏览器历史记录时页面不会自动重新加载,例如通过单击“历史返回按钮”。为什么页面没有自动重新加载?我可以改变这种行为吗?

这里有一小段代码来说明这个“问题”:

<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>

只需在文本字段中写入一些内容,浏览器历史记录就会相应更新。点击浏览器的历史返回按钮不会刷新页面。您必须手动刷新它。

我通过在运行window.history.back(); location.reload(); 的网站上插入我自己的“后退按钮”来解决这个问题。但如果普通浏览器的“历史后退按钮”也能做到这一点,我会很高兴。

【问题讨论】:

    标签: javascript browser-history pushstate


    【解决方案1】:

    我认为这可能比我更好地解释这个话题。 http://rosspenman.com/pushstate-jquery

    popstate 是关键

    我正在解决一个非常相似的问题。不要认为它漂亮,但以下 sn-p 或其变体可能会有所帮助

        $(window).on("popstate", function(e) {
            if (e.originalEvent.state !== null) {
            location.reload()
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多