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

Dav*_*och 614 javascript ajax google-chrome

我曾经梦想过chrome(开发者频道)实现了一种通过javascript(路径,而不是域)更新地址栏的方法,而无需重新加载页面,或者他们确实已经这样做了.

但是,我找不到我认为我读过的文章.

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

ps我不是在谈论window.location.hash,et al.如果上述情况存在,那么这个问题的答案将是不真实的.

Dav*_*och 841

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

这是我读过的原始文章(2010年7月10日发布):HTML5:更改浏览器URL而不刷新页面.

有关pushState/replaceState/popstate(也称为HTML5 History API)的更深入研究,请参阅MDN文档.

TL; DR,你可以这样做:

window.history.pushState("object or string", "Title", "/new-url");
Run Code Online (Sandbox Code Playgroud)

请参阅我的修改URL的答案,而不重新加载页面以获取基本操作方法.

  • Protip:你也可以使用带有这些函数的相对路径(例如`../ new-url`或`../../ new-url`.它们似乎至少可以在Chrome中做到你想要的. (10认同)
  • 这个现在由github使用,而树导航 (6认同)
  • 啊,功能在WebKit中并在几个月前登陆<https://bugs.webkit.org/show_bug.cgi?id=36152>.很好找! (3认同)
  • 我想补充一点,`window.replaceState` 更容易设置并且通常更可取,例如当您想在用户更改某些下拉或搜索字段的值后更新 URL 时。如果你想使用`pushState`,那么你还需要正确支持`onpopstate`事件。 (2认同)

Paw*_*wel 142

仅更改哈希 - 旧浏览器之后的内容

document.location.hash = 'lookAtMeNow';
Run Code Online (Sandbox Code Playgroud)

更改完整网址.Chrome,Firefox,IE10 +

history.pushState('data to be passed', 'Title of the page', '/test');
Run Code Online (Sandbox Code Playgroud)

以上将为历史记录添加一个新条目,以便您可以按"返回"按钮转到上一个状态.要在不添加新条目的情况下更改URL,请使用历史记录

history.replaceState('data to be passed', 'Title of the page', '/test');
Run Code Online (Sandbox Code Playgroud)

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

  • "replaceState"正是我所需要的,感谢扩展原始响应. (9认同)
  • 您不应该将绝对URL传递给此函数.如果你这样做,你很可能需要从当前的方案,主机和端口动态构建它 - 当你可以把它作为一个相对URL("foo.html"甚至"/foo.html"时,这是很多工作")让浏览器处理它. (3认同)

met*_*kum 31

更新到戴维斯的答案甚至检测到浏览器不支持pushstate:

if (history.pushState) {
  window.history.pushState("object or string", "Title", "/new-url");
} else {
  document.location.href = "/new-url";
}
Run Code Online (Sandbox Code Playgroud)

  • document.location.href重新加载页面 (4认同)

小智 10

var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?foo=bar';
window.history.pushState({path:newurl},'',newurl);
Run Code Online (Sandbox Code Playgroud)

  • 虽然此代码片段可以解决问题,但[包括解释](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而那些人可能不知道您建议代码的原因。 (9认同)
  • 建议编辑:const url = new URL(window.location); url.searchParams.set('foo', 'bar'); window.history.pushState({}, '', url); (4认同)