Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 可以使用pushState_Javascript_Pushstate - Fatal编程技术网

Javascript 可以使用pushState

Javascript 可以使用pushState,javascript,pushstate,Javascript,Pushstate,有人知道一个库可以决定是否可以使用pushState吗 我用的是: if(window.history.pushState){ window.history.pushState(null, document.title, path); }else{ location.pathname = path; } 但是我刚刚发现Safari 5.0.2中有一个bug,导致它无法工作,即使上面的测试通过了: 我想可能还有其他的陷阱,可能有人已经找到了它们并把它们包起来了,但我还没有找到任何

有人知道一个库可以决定是否可以使用pushState吗

我用的是:

if(window.history.pushState){
    window.history.pushState(null, document.title, path);
}else{
    location.pathname = path;
}
但是我刚刚发现Safari 5.0.2中有一个bug,导致它无法工作,即使上面的测试通过了:

我想可能还有其他的陷阱,可能有人已经找到了它们并把它们包起来了,但我还没有找到任何东西

编辑: @新月形新鲜

从我看到的情况来看,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版本。

pushState是其中的一部分。您可以使用常规JavaScript测试支持,如下所示:

if (typeof history.pushState !== "undefined") {
    // pushState is supported!
}
或者,您可以使用库:


查看Modernizer源代码,它是如何检查推送状态的:

  tests['history'] = function() {
      return !!(window.history && history.pushState);
  };
因此,一个简单的方法就是:

var hasPushstate = !!(window.history && history.pushState);

在深入两个级别之前,必须首先检查是否存在
window.history
,这可能就是您遇到错误的原因

链接页面的哪个部分说测试
window.history.pushState
无效?这个bug似乎与github正在做的事情有关(
pushState
结合设置
location.hash
,从我所能收集到的信息)。它实际上应该是(!!window.history&&&!!history.pushState)…(window.history&&history.pushState)本身将返回false/true…使用它没有意义!!在它之外..另一种选择是
window.history&&window.history中的“pushState”
var hasPushstate = !!(window.history && history.pushState);