代码之家  ›  专栏  ›  技术社区  ›  David Murdoch

使用新URL更新地址栏而不进行哈希或重新加载页面

  •  569
  • David Murdoch  · 技术社区  · 14 年前

    我梦见chrome(devchannel)实现了一种通过javascript(路径,而不是域)更新地址栏而不重新加载页面的方法,或者他们真的做到了这一点。

    但是,我找不到我喜欢的文章 认为

    我疯了还是有办法做到这一点(在Chrome中)?

    p、 我不是在说window.location.hash等,如果上面的内容存在的话 the answer to this question 将是不真实的。

    3 回复  |  直到 8 年前
        1
  •  920
  •   Cavell Blood David Murdoch    6 年前

    您现在可以在大多数“现代”浏览器中执行此操作!

    以下是我读到的原文(2010年7月10日发布): HTML5: Changing the browser-URL without refreshing page .

    更深入地了解pushState/replaceState/popstate(又称HTML5历史API) see the MDN docs .

    window.history.pushState("object or string", "Title", "/new-url");
    

    看看我的答案 Modify the URL without reloading the page 基本操作方法。

        2
  •  175
  •   Pawel    7 年前

    document.location.hash = 'lookAtMeNow';
    

    正在更改完整URL。Chrome、Firefox、IE10+

    history.pushState('data to be passed', 'Title of the page', '/test');
    

    history.replaceState('data to be passed', 'Title of the page', '/test');
    

    现在试着在控制台中运行这些!

        3
  •  36
  •   KenBuckley metamagikum    6 年前

    更新Davids answer,甚至可以检测不支持pushstate的浏览器:

    if (history.pushState) {
      window.history.pushState("object or string", "Title", "/new-url");
    } else {
      document.location.href = "/new-url";
    }
    
        4
  •  8
  •   Kevin Mendez    5 年前
    var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?foo=bar';
    window.history.pushState({path:newurl},'',newurl);