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

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

我只需要更改域之后的部分,所以我不会违反跨域策略。

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

当前回答

parent.location.hash = "hello";

其他回答

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

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

这将“破坏”后退按钮功能。在某些情况下,这可能是必需的,例如图像库(您希望后退按钮返回到库索引页,而不是返回到您查看的每个图像),同时为每个图像提供自己的唯一url。

parent.location.hash = "hello";

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

下面是在不重新加载页面的情况下更改URL的功能。它仅支持HTML5。

  function ChangeUrl(page, url) {
        if (typeof (history.pushState) != "undefined") {
            var obj = {Page: page, Url: url};
            history.pushState(obj, obj.Page, obj.Url);
        } else {
            window.location.href = "homePage";
            // alert("Browser does not support HTML5.");
        }
    }

  ChangeUrl('Page1', 'homePage');

这就是无需重新加载即可导航的全部内容

//添加设置而不重新加载location.hash=“设置”;//如果url随哈希更改,请执行某些操作window.addEventListener('hashchange',()=>{console.log('rl哈希已更改!');});//如果url更改,请执行某些操作(不要使用哈希检测更改)//window.addEventListener('locationchange',function(){//console.log('rl已更改!');//})//删除#设置而不重新加载history.back();