如何在不重新加载页面的情况下修改URL?

JavaScript

飞云Tom小宇宙

2020-03-09

有没有办法可以在不重新加载页面的情况下修改当前页面的URL?

如果可能,我想访问#哈希之前部分

我只需要更改的部分,所以就好像我没有违反跨域策略一样。

 window.location.href = "www.mysite.com/page2.php";  // Sadly this reloads

第194篇《如何在不重新加载页面的情况下修改URL?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

9个回答
null 2020.03.09

Use history.pushState() from the HTML 5 History API.

Refer to the HTML5 History API for more details.

A达蒙 2020.03.09

Any changes of the loction (either window.location or document.location) will cause a request on that new URL, if you’re not just changing the URL fragment. If you change the URL, you change the URL.

Use server-side URL rewrite techniques like Apache’s mod_rewrite if you don’t like the URLs you are currently using.

JinJin阿飞番长 2020.03.09

You can add anchor tags. I use this on my site so that I can track with Google Analytics what people are visiting on the page.

I just add an anchor tag and then the part of the page I want to track:

var trackCode = "/#" + urlencode($("myDiv").text());
window.location.href = "http://www.piano-chords.net" + trackCode;
pageTracker._trackPageview(trackCode);
神无宝儿达蒙 2020.03.09

Before HTML5 we can use:

parent.location.hash = "hello";

and:

window.location.replace("http:www.example.com");

This method will reload your page, but HTML5 introduced the history.pushState(page, caption, replace_url) that should not reload your page.

小小猴子 2020.03.09
parent.location.hash = "hello";
ItachiJinJin 2020.03.09

如Vivart和geo1701所述,HTML5 replaceState是答案。但是,并非所有浏览器/版本都支持该功能。 History.js包装了HTML5状态功能,并为HTML4浏览器提供了额外的支持。

YLD 2020.03.09

注意:如果使用的是HTML5浏览器,则应忽略此答案。如其他答案所示,现在这是可能的。

There is no way to modify the URL in the browser without reloading the page. The URL represents what the last loaded page was. If you change it (document.location) then it will reload the page.

One obvious reason being, you write a site on www.mysite.com that looks like a bank login page. Then you change the browser URL bar to say www.mybank.com. The user will be totally unaware that they are really looking at www.mysite.com.

神无猪猪 2020.03.09

这是我的解决方案(newUrl是您要用当前URL替换的新URL):

history.pushState({}, null, newUrl);
老丝Gil樱 2020.03.09

如果要更改URL但又不想将条目添加到浏览器历史记录中,则也可以使用HTML5 replaceState

if (window.history.replaceState) {
   //prevents browser from storing history with each change:
   window.history.replaceState(statedata, title, url);
}

这将“破坏”后退按钮的功能。在某些情况下可能需要这样做,例如图片库(您希望后退按钮返回到图片库索引页面,而不是在浏览的每个图像中都回退),同时为每个图像提供自己的唯一网址。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android