11

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 のバージョンでも機能します。

4

2 に答える 2

24

Modernizer のソース コードを見ると、プッシュ状態をチェックする方法は次のとおりです。

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

したがって、簡単な方法は次のとおりです。

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

window.history2 レベル深く進む前に、まず の存在を確認する必要があります。これが、おそらくエラーが発生した理由です。

于 2012-05-18T05:56:54.780 に答える
16

pushState はHTML5 History APIの一部です。次のように、通常の JavaScript を使用してサポートをテストできます。

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

または、 Modernizrライブラリを使用できます。

if (Modernizr.history) {
     // pushState is supported!
}
于 2011-11-01T05:23:01.247 に答える