Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify the URL without reloading the page?

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 
like image 468
Robin Rodricks Avatar asked May 05 '09 10:05

Robin Rodricks


People also ask

How do I change URL without refresh?

history. pushState(nextState, nextTitle, nextURL); // This will replace the current entry in the browser's history, without reloading window.

How do I use JavaScript to modify the URL without reloading the page?

the page using JavaScript? the page using JavaScript? Method 2: Adding a new state with pushState() Method: The pushState() method is used to add a new history entry with the properties passed as parameters. This will change the current URL to the new state given without reloading the page.


1 Answers

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 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.

like image 89
David Murdoch Avatar answered Sep 22 '22 06:09

David Murdoch