javascript 可以使用 pushState

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4966090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:30:30  来源:igfitidea点击:

Can use pushState

javascriptpushstate

提问by keegan3d

Does anyone know of a library that determines if pushState can be used?

有谁知道确定是否可以使用 pushState 的库?

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.

但我刚刚发现 Safari 5.0.2 中存在一个错误,即使上述测试通过,它也无法工作: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

编辑:@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.

从我所看到的,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);
}

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.

在 Safari 5.0.2 中,当 pushState 更改 url 时,location.pathname 不会更改。这适用于其他浏览器和 Safari 版本。

回答by Mauvis Ledford

Looking at the Modernizer source code this is how it checks for push state:

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

  tests['history'] = function() {
      return !!(window.history && history.pushState);
  };

So a simple way for you would just be:

所以对你来说一个简单的方法就是:

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

One must first check for the existence of window.historybefore going two levels deep and that's probably why you were experiencing an error.

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

回答by dbau

pushState is part of the HTML5 History API. You can test for support using regular JavaScript like so:

pushState 是HTML5 History API 的一部分。您可以使用常规 JavaScript 来测试支持情况,如下所示:

if (typeof history.pushState !== "undefined") {
    // pushState is supported!
}

Alternatively, you can use the Modernizrlibrary:

或者,您可以使用Modernizr库:

if (Modernizr.history) {
     // pushState is supported!
}