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

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

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

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

当前回答

您可以在应用程序的任何位置使用这个美丽而简单的功能。

function changeurl(url, title) {
    var new_url = '/' + url;
    window.history.pushState('data', title, new_url);
    
}

您不仅可以编辑URL,还可以同时更新标题。

其他回答

这现在可以在Chrome、Safari、Firefox 4+和Internet Explorer 10pp4+中完成!

有关详细信息,请参阅此问题的答案:使用新的URL更新地址栏,而无需哈希或重新加载页面

例子:

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

然后,您可以使用window.onpopstate检测后退/前进按钮导航:

window.onpopstate = function(e){
    if(e.state){
        document.getElementById("content").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
    }
};

有关操纵浏览器历史的更深入了解,请参阅MDN文章。

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

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

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

可以添加定位标记。我在我的网站上使用这个,这样我就可以通过Google Analytics跟踪人们在页面上访问的内容。

我只是添加了一个锚标记,然后添加了我要跟踪的页面部分:

var trackCode = "/#" + urlencode($("myDiv").text());
window.location.href = "http://www.piano-chords.net" + trackCode;
pageTracker._trackPageview(trackCode);

您可以在应用程序的任何位置使用这个美丽而简单的功能。

function changeurl(url, title) {
    var new_url = '/' + url;
    window.history.pushState('data', title, new_url);
    
}

您不仅可以编辑URL,还可以同时更新标题。

parent.location.hash = "hello";