Monday, June 3, 2013

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
share|edit
1
Can you give more details please? Such as an example scenario of doing that or your requirement.. Then it would be easy to answer :) – Chathuranga Chandrasekara May 5 '09 at 10:56
Easy? I don't even know if this is possible in JS, without triggering a page reload in the browser. – JarvisMay 5 '09 at 10:57
You can do this in Flash. You would just need a little background App, and pass your JavaScript to the flash to modify the location bar. – Nick Berardi Dec 14 '09 at 3:55
8
Just to make it easier to understand the question, this is what Facebook does when you open a photo, for example. The url bar changes to point DIRECTLY to that photo, so you can share the URL without losing where you are in the site. Remember sites based on framing last decade? You could only get the homepage url, because only internal frames were changing. And that was terrible. – Spidey Apr 19 '12 at 17:59

13 Answers


up vote391down voteaccepted
This can now be done in Chrome, Safari, FF4+, and IE10pp4+!
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.
share|edit
3
perfect. thank you. – bobsoap Sep 17 '11 at 4:45
3
Hope very much, that IE10 will support this. Thanks for the answer! – manakor Oct 3 '11 at 17:52
35
How does facebook do it in IE7 then? – infensus May 1 '12 at 9:35
5
@CHiRiLo check out history.js which provides a fallback for browsers that don't support the HTML5 history API. – David Murdoch Sep 19 '12 at 22:21
2
@infensus If there's a # sign in the URL somewhere, that trick has existed for years.. – Izkata Nov 8 '12 at 22:26
show 11 more comments

No comments:

Post a Comment