历史推送状态不在独立的 location.hash 或 location.href 中,而是在 Location 对象本
History pushed state is not in standalone location.hash or location.href but is in Location object itself
谁能解释这种行为?我使用 history.pushState(null, null, '#test');
推送历史状态。然后,当尝试使用 console.log(window.location.hash)
在侦听器函数中获取状态 URL(没有找到更好的方法来侦听 pushState 更改)时,它会返回空字符串#test
哈希。 console.log(window.location.href)
也返回没有哈希#test
的整个 URL,但console.log(window.location)
返回哈希位于href
和hash
属性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');
相关文章:
- 引用对象中的通用值
- jQuery匹配JSON对象的部分文本
- 节点导出返回一个空对象
- 如何在Javascript中将JSon对象转换为数组
- 我可以在json对象中添加一个函数吗
- 使用JS将数组转换为json对象
- 全局变量和全局对象的属性之间有什么区别吗
- 比较从函数和生成的日期对象
- 对象.在document.location上进行观测
- 历史推送状态不在独立的 location.hash 或 location.href 中,而是在 Location 对象本
- 如何从外部窗口对象获取 location.href
- javascript中“location”对象的比较
- 正在检测iframe对象中的src/location更改
- 如何“;转换“;window.location.pathname从对象到字符串
- 为什么用windows.location重定向到新的URL后会有一个额外的对象
- 如何将纬度和经度(从gps方法)转换为几何图形.location谷歌地图对象
- jsf中的Javascript location对象
- 如何将字符串转换为Location对象
- 对象函数(){location.href=this.options.url);没有方法'apply'
- 如何修改/“;Spoof“;运行时的标准浏览器JS DOM对象(Window.location)