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

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

问题描述:

有没有一种方法可以修改当前页面的URL而无需重新加载页面?

Is there a way I can modify the URL of the current page without reloading the page?

如果可能的话,我想访问之前部分.

I would like to access the portion before the # hash if possible.

我只需要在域的之后进行更改,所以这并不像我在违反跨域策略.

I only need to change the portion after the domain, so it's not like I'm violating cross-domain policies.

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

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

This can now be done in Chrome, Safari, Firefox 4+, and Internet Explorer 10pp4+!

有关更多信息,请参见此问题的答案: 用新的地址栏更新不带哈希值或不重新加载页面的URL

See this question's answer for more information: Updating address bar with new URL without hash or reloading the page

示例:

 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检测后退/前进按钮导航:

You can then use window.onpopstate to detect the back/forward button navigation:

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


要更深入地了解操纵浏览器历史记录,请参见 查看更多