【问题标题】:How can I use window.history.pushState 'safely'如何“安全地”使用 window.history.pushState
【发布时间】:2011-06-29 04:04:44
【问题描述】:

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

TypeError:history.pushState 不是函数

如何避免这种情况?

【问题讨论】:

    标签: javascript html try-catch


    【解决方案1】:

    History API 确实存在垫片。 History.js 使用 HTML4 的 hashchange 事件和文档片段标识符来模仿旧浏览器中的历史 API。如果现代浏览器使用其中一个哈希 URL,它会使用 replaceState 悄悄地更正 URL。

    如果您不担心它无法在旧版浏览器中运行,并且只想使用它而不会引发错误,我会这样做...

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

    这会在尝试使用之前检查历史记录和 pushstate 函数是否存在。

    【讨论】:

      【解决方案2】:

      虽然我没有在 JavaScript 中测试过它,但我知道在其他语言中 try-catch 比简单的 if... 更耗费资源......

      用途:

      if(history.pushState) {
          history.pushState({"id":100}, document.title, location.href);
      }
      

      请记住,当您单击后退按钮时,除非您实现 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
          };
      }
      

      【讨论】:

      • 注意:history.popstate 被调用一次 - 在第一页加载时立即调用:这是设计使然。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2012-11-01
        • 2017-06-21
        • 2016-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        相关资源
        最近更新 更多