javascript 无需重新加载页面即可更改浏览器栏中的 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19193335/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:43:43  来源:igfitidea点击:

Change the url in browser bar without reloading page

javascripturl

提问by Axeem

I want to change the url in browser bar without reloading page.

我想在不重新加载页面的情况下更改浏览器栏中的 url。

<html><head>
 <title>Change url in browser bar</title>
</head>
     <body>
             <h1>Refresh page to see our other website</h1>
     </body>
 </html>

When any user enter my website like www.a-site.comAfter open this site he see the text Refresh page to see our other website. Can I do that when he enter in www.a-site.com, after this url change in browser bar like www.b-site.comand when user refresh page it can automaticaaly redirect in
www.b-site.com. can this is possible.
Thanks...............

当任何用户进入我的网站时,如www.a-site.com打开此网站后,他会看到文本 刷新页面以查看我们的其他网站。当他输入www.a-site.com 时,我可以这样做吗,在浏览器栏中更改此 url 后,例如www.b-site.com并且当用户刷新页面时,它可以自动重定向到
www.b-site.com。这可能吗。
谢谢...............

回答by underscore

You are looking for following

您正在寻找以下

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

Here is the original article I read (posted July 10, 2012): HTML5: Changing the browser-URL without refreshing page.

这是我阅读的原始文章(2012 年 7 月 10 日发布):HTML5:在不刷新页面的情况下更改浏览器 URL。

Example:

例子:

 function processAjaxData(response, urlPath){
     document.getElementById("content").innerHTML = response.html;
     document.title = response.pageTitle;
     window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
 }

Documentation

文档