我怎样才能'安全'使用window.history.pushState

Roc*_*och 20 javascript html5 try-catch

我想window.history.pushState()在支持浏览器时使用该功能.不幸的是我在Firefox上收到错误:

TypeError:history.pushState不是函数

怎么可能避免这种情况?

Lev*_*son 24

虽然我没有在JavaScript中测试它,但我知道在其他语言中try-catch比简单的如果...

使用:

if(history.pushState) {
    history.pushState({"id":100}, document.title, location.href);
}
Run Code Online (Sandbox Code Playgroud)

请记住,当您单击后退按钮时,除非您实施,否则实际上不会发生任何事情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
    };
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:history.popstate被调用一次 - 在第一页加载时立即调用:这是设计的. (4认同)

Fre*_*ing 19

[try-catch]标签意味着你已经知道了答案...(有什么更具体的吗?)另一个可能性是检查 if ( history.pushState ) history.pushState( {}, document.title, location.href );