pushState& popState:Safari 5没有返回window.history.state

时间:2012-06-08 00:10:13

标签: javascript browser-history pushstate popstate

在Safari 5中触发popState时,我似乎无法访问window.history.state对象(页面返回)。此代码在Chrome 19和Firefox 12中完美运行。

window.onload = function() {

     window.setTimeout(function() {

          var original = window.location.href;

          window.addEventListener("popstate", function(e) {

                    if (window.history.state !== null) {
                        var type = window.history.state.type;
                        var page = window.history.state.page;
                        //custom Ajax function below
                        getContent({type:type, page:page, category: category}, '/' + type + '/' + page);
                    } else {
                        window.location = original;
                    }

            }, false);

     }, 1);
}
Safari 5中的

console.log(window.history.state)返回'undefined'。

2 个答案:

答案 0 :(得分:3)

window.history.state is only available in some browsers. It's not part of the spec per se.

Feature           │ Chrome  │ Firefox (Gecko)  │  IE  │ Opera  │ Safari
──────────────────┼─────────┼──────────────────┼──────┼────────┼───────
replace/pushState │   5     │    4.0 (2.0)     │  10  │ 11.50  │  5.0
history.state     │  18     │    4.0 (2.0)     │  10  │ 11.50  │  ---

答案 1 :(得分:2)

因此,如果支持history.state,那么该值将为null(如果浏览器正在记住状态,则为对象),否则将是未定义的。我最终得到了这段代码,以检查它是否支持

(window.history && history.pushState && history.state !== undefined) 
? true : false;

在最新的Chrome,Safari 5,6,IE 9中测试