可以使用pushState
有谁知道有一个库可以确定是否可以使用pushState?
我正在使用这个:
if(window.history.pushState){
window.history.pushState(null, document.title, path);
}else{
location.pathname = path;
}
但我刚刚发现 Safari 5.0.2 中有一个错误,导致即使上述测试通过也无法工作: http://support.github.com/discussions/site/2263-line-links-broken。
我认为可能还有其他陷阱,并且可能已经有人找到它们并将它们包裹起来,但我还没有找到任何东西。
编辑: @Crescent Fresh
从我所看到的看来,pushState 会推送到历史堆栈并更改 url,但不会更新 location.pathname。在我的代码中,我使用 setInterval 来检查路径是否已更新。
var cachedPathname = location.pathname;
if(window.history.pushState){
cachedPathname = location.pathname;
setInterval(function(){
if(cachedPathname !== location.pathname){
cachedPathname = location.pathname;
//do stuff
}
}, 100);
}
在 Safari 5.0.2 中,当 pushState 更改 url 时,location.pathname 不会更改。这适用于其他浏览器和 Safari 版本。
Does anyone know of a library that determines if pushState can be used?
I was using this:
if(window.history.pushState){
window.history.pushState(null, document.title, path);
}else{
location.pathname = path;
}
But I just found out that there is a bug in Safari 5.0.2 that causes it not to work even though the above test passes: http://support.github.com/discussions/site/2263-line-links-broken.
I'm thinking there might be other gotchas and someone has probably already found them and wrapped em up but I haven't found anything yet.
Edit:
@Crescent Fresh
From what I've seen it seems like pushState pushes onto the history stack and changes the url but doesn't update location.pathname. In my code I'm using setInterval to check if the path has updated.
var cachedPathname = location.pathname;
if(window.history.pushState){
cachedPathname = location.pathname;
setInterval(function(){
if(cachedPathname !== location.pathname){
cachedPathname = location.pathname;
//do stuff
}
}, 100);
}
In Safari 5.0.2 the location.pathname doesn't change when pushState changes the url. This works in other browsers and versions of Safari.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 Modernizer 源代码,这就是它检查推送状态的方式:
因此,对您来说,一种简单的方法是:
在深入两层之前,必须首先检查
window.history
是否存在,这就是可能是您遇到错误的原因。Looking at the Modernizer source code this is how it checks for push state:
So a simple way for you would just be:
One must first check for the existence of
window.history
before going two levels deep and that's probably why you were experiencing an error.PushState 是 HTML5 History API 的一部分。您可以使用常规 JavaScript 来测试支持,如下所示:
或者,您可以使用 Modernizr 库:
pushState is part of the HTML5 History API. You can test for support using regular JavaScript like so:
Alternatively, you can use the Modernizr library: