Javascript 如何使用window.history.pushState';安全地';

Javascript 如何使用window.history.pushState';安全地';,javascript,html,try-catch,Javascript,Html,Try Catch,我想在支持浏览器中使用window.history.pushState()函数。不幸的是,我在Firefox上遇到了一个错误: TypeError:history.pushState不是函数 如何避免这种情况呢?[try catch]标签暗示了您已经知道答案的含义。。。(还有更具体的吗?) 另一种可能是检查if(history.pushState)history.pushState({},document.title,location.href)虽然我还没有在JavaScript中测试过它,但我

我想在支持浏览器中使用
window.history.pushState()
函数。不幸的是,我在Firefox上遇到了一个错误:

TypeError:history.pushState不是函数


如何避免这种情况呢?

[try catch]标签暗示了您已经知道答案的含义。。。(还有更具体的吗?)
另一种可能是检查
if(history.pushState)history.pushState({},document.title,location.href)

虽然我还没有在JavaScript中测试过它,但我知道在其他语言中,try catch比简单的if

使用:

请记住,单击“上一步”按钮时,除非实现
window.onpopstate
,否则实际上不会发生任何事情。您需要传入获取内容所需的数据:

if(history.pushState && history.replaceState) {
    //push current id, title and url
    history.pushState({"id":100}, document.title, location.href);

    //push new information
    history.pushState({"id":101}, "new title", "/new-url/");

    //this executes when you use the back button
    window.onpopstate = function(e) {
        alert(e.state.id);
        //perhaps use an ajax call to update content based on the e.state.id
    };
}

历史API确实存在一个垫片。使用HTML4的hashchange事件和文档片段标识符来模拟旧浏览器中的历史API。如果现代浏览器使用其中一个散列URL,它将使用replaceState安静地更正URL

如果您不担心它在旧浏览器中不工作,并且您只想使用它而不抛出错误,我会这样做

window.history && window.history.pushState && window.history.pushState("", "", url);

这将检查历史记录和pushstate函数是否存在,然后再尝试使用它。

注意:history.popstate只调用一次-在第一页加载时立即调用:这是设计的。
window.history && window.history.pushState && window.history.pushState("", "", url);