有谁知道确定是否可以使用 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 .
我在想可能还有其他陷阱,可能有人已经找到并解决了这些问题,但我还没有找到任何东西。
编辑: @新月新鲜
据我所见,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 版本。
最佳答案
查看 Modernizer 源代码,这是它检查推送状态的方式:
tests['history'] = function() {
return !!(window.history && history.pushState);
};
对你来说一个简单的方法就是:
var hasPushstate = !!(window.history && history.pushState);
必须先检查 window.history
是否存在,然后再深入两层,这可能就是您遇到错误的原因。
关于javascript - 可以使用 pushState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4966090/