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

History pushed state is not in standalone location.hash or location.href but is in Location object itself

本文关键字:location 对象 Location href hash 状态 独立 历史      更新时间:2023-09-26

谁能解释这种行为?我使用 history.pushState(null, null, '#test'); 推送历史状态。然后,当尝试使用 console.log(window.location.hash) 在侦听器函数中获取状态 URL(没有找到更好的方法来侦听 pushState 更改)时,它会返回空字符串#test哈希。 console.log(window.location.href)也返回没有哈希#test的整个 URL,但console.log(window.location)返回哈希位于hrefhash属性Location的对象。为什么会这样,我怎样才能获取推送状态的 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');

这是因为您在实际设置新状态之前记录变量。之所以可以在对象中看到更新的属性,是因为它记录了对对象的引用,而不是记录对象的副本。您的猴子补丁直到这一行才会调用原始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');