Javascript 使用新 URL 更新地址栏,无需散列或重新加载页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3338642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Updating address bar with new URL without hash or reloading the page
提问by David Murdoch
I either dreamt about chrome (dev channel) implementing a way to update the address bar via javascript (the path, not domain) without reloading the page or they really have done this.
我要么梦想着 chrome(开发频道)实现一种通过 javascript(路径,而不是域)更新地址栏的方法,而无需重新加载页面,要么他们真的做到了。
However, I can't find the article I thinkI read.
但是,我找不到我认为我读过的文章。
Am I crazy or is there a way to do this (in Chrome)?
我疯了还是有办法做到这一点(在 Chrome 中)?
p.s. I'm not talking about window.location.hash, et al. If the above exists the answer to this questionwill be untrue.
ps 我不是在谈论 window.location.hash 等。如果上述情况存在,那么这个问题的答案将是不真实的。
回答by David Murdoch
You can now do this in most "modern" browsers!
您现在可以在大多数“现代”浏览器中执行此操作!
Here is the original article I read (posted July 10, 2010): HTML5: Changing the browser-URL without refreshing page.
这是我阅读的原始文章(2010 年 7 月 10 日发布):HTML5:在不刷新页面的情况下更改浏览器 URL。
For a more in-depth look into pushState/replaceState/popstate (aka the HTML5 History API) see the MDN docs.
要更深入地了解 pushState/replaceState/popstate(又名 HTML5 History API),请参阅 MDN 文档。
TL;DR, you can do this:
TL; DR,你可以这样做:
window.history.pushState("object or string", "Title", "/new-url");
See my answer to Modify the URL without reloading the pagefor a basic how-to.
有关基本操作方法,请参阅我在不重新加载页面的情况下修改 URL 的答案。
回答by Pawel
Changing only what's after hash - old browsers
仅更改哈希后的内容 - 旧浏览器
document.location.hash = 'lookAtMeNow';
Changing full URL. Chrome, Firefox, IE10+
更改完整网址。铬、火狐、IE10+
history.pushState('data to be passed', 'Title of the page', '/test');
The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use
以上将向历史记录添加一个新条目,因此您可以按“返回”按钮转到之前的状态。要在不向历史记录中添加新条目的情况下更改 URL
history.replaceState('data to be passed', 'Title of the page', '/test');
Try running these in the console now!
现在尝试在控制台中运行这些!
回答by metamagikum
Update to Davids answer to even detect browsers that do not support pushstate:
更新到 Davids 答案甚至可以检测不支持 pushstate 的浏览器:
if (history.pushState) {
window.history.pushState("object or string", "Title", "/new-url");
} else {
document.location.href = "/new-url";
}
回答by Kevin Mendez
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?foo=bar';
window.history.pushState({path:newurl},'',newurl);

