历史推送状态不在独立的location.hash或location.href中,而是在Location对象本身中

时间:2015-03-16 00:49:53

标签: javascript html5 pushstate html5-history

任何人都可以解释这种行为吗?我使用history.pushState(null, null, '#test');推送历史状态。然后,当尝试使用console.log(window.location.hash)在侦听器函数中获取状态URL(没有找到更好的方法来监听pushState更改)时,它返回空字符串#test哈希。 console.log(window.location.href)也返回整个网址而不包含哈希#test,但console.log(window.location)返回Location对象,其中哈希位于hrefhash属性中。为什么这样,我如何获得推送状态的URL?

        (function(history){
            var pushState = history.pushState;
            history.pushState = function(state) {
                if (typeof history.onpushstate == "function") {
                    history.onpushstate({state: state});
                }
                console.log(window.location.hash);
                console.log(window.location.href);
                console.log(window.location);
                return pushState.apply(history, arguments);
            }
        })(window.history);

        history.pushState(null, null, '#test');

1 个答案:

答案 0 :(得分:2)

这是因为您在实际设置新状态之前记录变量。您可以在对象中看到更新的属性的原因,因为它记录了对象的引用,而不是记录对象的副本。你的猴子补丁在此行之前不会调用原始的pushState函数。

return pushState.apply(history, arguments);

要解决此问题,您可以在记录之前简单地调用该函数,然后返回响应。

(function(history){
    var pushState = history.pushState;
    history.pushState = function(state) {
        if (typeof history.onpushstate == "function") {
            history.onpushstate({state: state});
        }
        var r = pushState.apply(history, arguments);
        console.log(window.location.hash);
        console.log(window.location.href);
        console.log(window.location);
        return r;
    }
})(window.history);

history.pushState(null, null, '#test');