javascript - How do I modify the URL without reloading the page?

ID : 233

viewed : 229

Tags : javascripthtmlurlurl-rewritingfriendly-urljavascript

Top 5 Answer for javascript - How do I modify the URL without reloading the page?

vote vote


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


 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.

vote vote


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

vote vote


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.

vote vote


Here is my solution (newUrl is your new URL which you want to replace with the current one):

history.pushState({}, null, newUrl); 
vote vote


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 that looks like a bank login page. Then you change the browser URL bar to say The user will be totally unaware that they are really looking at

Top 3 video Explaining javascript - How do I modify the URL without reloading the page?