How do I modify the URL without reloading the page?

3.1k2009 年提問 · Robin Rodricks ·javascripthtmlurlurl-rewritingfriendly-url 主題:DOM、事件、表單與 jQuery → 在 Stack Overflow 看原文 ↗

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";  // this reloads

重點答案

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

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

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);
 }

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

window.addEventListener("popstate", (e) => {
    if(e.state){
        document.getElementById("content").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
    }
});

For a more in-depth look at manipulating browser history, see this MDN article.

You can also use HTML5 replaceState if you want to change the url but don't want to add the entry to the browser history:

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

This would 'break' the back button functionality. This may be required in some instances such as an image gallery (where you want the back button to return back to the gallery index page instead of moving back through each and every image you viewed) whilst giving each image its own unique url.