Modify the URL without reloading the page

Is there any 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 its not like I'm violating cross-domain policies.

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

This can now be done in Chrome, Safari, FF4+, and IE10pp4+!

See this question's answer for more info: 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 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;
    }
};

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


HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you to add and modify history entries, respectively.

window.history.pushState('page2', 'Title', '/page2.php');

Read more about this from here


NOTE: If you are working with an HTML5 browser then you should ignore this answer. This is now possible as can be seen in the other answers.

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 .

链接地址: http://www.djcxy.com/p/12096.html

上一篇: URL中的方括号会导致Tomcat中的异常

下一篇: 修改网址而不重新加载页面