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
upvote
  flag
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
83 upvote
  flag
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

18 Answers 11

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.

20 upvote
  flag
I don't want to change the domain, only the path and file name. – Robin Rodricks
4 upvote
  flag
This still doesn't stop potential security risks as the browser has no idea that domain/mysite and domain/othersite are both considered "safe" by the user. Maybe the question should be why do you want to change the URL? If it is to obscure it from the user, you could simply run your application within an iframe. – Robin Day
4 upvote
  flag
You can actually do this with Flash. It will allow you to modify the URL without making a request. This is possible because Flash operates outside of the browser, but very tightly with it. – Nick Berardi
1 upvote
  flag
you can change hash / fragment, but definitely not the location / path. – dusoft
126 upvote
  flag
I have to say there are perfectly valid reasons for wanting to modify the URL in the address bar client-side. For instance, if you have a table of data with paging, sorting and filtering, and want those things to be Ajax powered, but still update the URL so that the current state of the page is bookmarkable. I can understand the security risks with modifying the domain name (phishing etc.), but why don't browsers allow just the part of the URL to the right of the top level domain to be modifiable via script? – Sunday Ironfoot
35 upvote
  flag
this answer is no longer 100% true. See my answer for details. – David Murdoch
3 upvote
  flag
The use case is indeed when using Ajax, you may display another document but do not want to reload, yet you want the document to be bookmarkable. In these cases one would like to change the path of the URL without changing the domain, which should be fine from a security standpoint. – Jean Vincent
1 upvote
  flag
wondering how facebook's photo viewer modifies the url on next/previous navigation without reloading the entire page but only the image. They are not changing the #hash but the query string (?id=query_string) Is that html5? – Mat J
1 upvote
  flag
If there is no way to do this then how this is implemented in google+ photos. There, when you click on the next photo(in fullscreen view) url changed but page not reloaded, and only needed image is uploaded. – Andrey Nikishaev
upvote
  flag
@SundayIronfoot If the browser allows to change part of URL to the right of the top level domain, then someone using online proxies (like free-proxy-online.appspot.com) could become a victim of phishing attack. – Parag Gangil

Any changes of the loction (either window.location or document.location) will cause a request on that new URL, if you’re not just changing the URL fragment. If you change the URL, you change the URL.

Use server-side URL rewrite techniques like Apache’s mod_rewrite if you don’t like the URLs you are currently using.

upvote
  flag
Can I use "location.pathname"?? – Robin Rodricks
3 upvote
  flag
No, changing that attribute will cause a request too. – Gumbo

Assuming you're not trying to do something malicious, anything you'd like to do to your own URLs can be magicked into being with htaccess.

7 upvote
  flag
htaccess only works with server requests. Hashtags are not sent to the server, therefore htaccess rewriting can not work. – samvermette
parent.location.hash = "hello";
9 upvote
  flag
I want to change the URL, not just the hash -- #mydata – Robin Rodricks
33 upvote
  flag
Changing the hash can be useful in ajax as it's a kind of state without using cookies, is bookmarkable, and compatible with browser back buttons. Gmail uses this nowadays to make it more browser friendly. – Matthew Lock
upvote
  flag
@Jarvis: what is the difference? – noisy
upvote
  flag
@noisy Server side tracking cannot see hashes unless sent to the tracking service explicitly. – RedYetiCo
upvote
  flag
this is not useful if you're using an mvc framework that routes on hash, for example backbone. – catbadger

You can add anchor tags. I use this on my site http://www.piano-chords.net/ so that I can track with google analytics what people are visiting on the page. I just add an anchor tag and then the part of the page I want to track.

var trackCode = "/#" + urlencode($("myDiv").text());
window.location.href = "http://www.piano-chords.net" + trackCode;
pageTracker._trackPageview(trackCode);
1 upvote
  flag
How does that work with search engine indexing? – OIS
up vote 1522 down vote accepted

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.

4 upvote
  flag
Hope very much, that IE10 will support this. Thanks for the answer! – Nik Sumeiko
2 upvote
  flag
@manakor "This can now be done in Chrome, Safari, FF4+, and IE10pp3+!" ... Looks like it will. – David Murdoch
221 upvote
  flag
How does facebook do it in IE7 then? – Dominic Tobias
2 upvote
  flag
Sadly, this is not working on IE9. – Tsukimoto Mitsumasa
45 upvote
  flag
@CHiRiLo check out history.js which provides a fallback for browsers that don't support the HTML5 history API. – David Murdoch
19 upvote
  flag
@infensus If there's a # sign in the URL somewhere, that trick has existed for years.. – Izkata
21 upvote
  flag
What does the "pp4+" part of "IE10pp4+" mean? – Scott David Tesler
23 upvote
  flag
platform preview 4 – David Murdoch
upvote
  flag
will a button should call the 'processAjaxData' method? – user962206
upvote
  flag
@DavidMurdoch is the processAjaxData method should be placed inside an event?? – user962206
upvote
  flag
could you explain in more detail about the processAjaxData() function? – think123
2 upvote
  flag
processAjaxData is just an example; it is only meant to show you a typical use-case for history.pushState. – David Murdoch
upvote
  flag
then how would the response object work? – think123
upvote
  flag
Can you know when the back and when the forward button is pressed? – Alvaro
upvote
  flag
Is there an opportunity to load the fragment into the content div again when I refresh the page manually? – trek711
upvote
  flag
@Izkata can you explain me how to do it with the # sign ? – LeSam
4 upvote
  flag
@user2372006 Not a chance of it here. Try asking a question. – Izkata
upvote
  flag
using your function, my page title returns undefined as does the content html. – user2166538
upvote
  flag
How is the processAjaxData supposed to be called? Is the idea that the caller has already extracted the page title and html and put them into a { pageTitle: ..., html: ... } object, or is that the interface already provided by some built-in object? – Jeremy Banks
upvote
  flag
In this example, the AJAX data's response object IS { pageTitle: ..., html: ... }; in other words: that object was put together by the server and sent in response to the XHR request. – David Murdoch
1 upvote
  flag
e.state can also be e.originalEvent.state in my case – pascalvgemert
2 upvote
  flag
how to call this function ?? i mean what to put in response ?? – sonam Sharma
upvote
  flag
@ScottDavidTesler May be pp4+ means public preview 4+ – Ankit
2 upvote
  flag
What's response? – HoldOffHunger
upvote
  flag
Does the URL have to be an absolute path, or can it be relative? – Dan Nissenbaum
upvote
  flag
I've answered my own question - yes (and see Vivart's answer below). – Dan Nissenbaum

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

7 upvote
  flag
May not work on file:/// for safety reasons, e.g. Firefox 30. Test on localhost with python -m SimpleHTTPServer. – Ciro Santilli 华涌低端人口 六四事件 法轮功
upvote
  flag
Exactly what I needed. Thanks. – HoldOffHunger
1 upvote
  flag
I used this on codeigniter. – jned29
4 upvote
  flag
The first parameter is expected to be an object, not just a string. – Alexis Wilke
9 upvote
  flag
IMO this is really the best answer. If all you want to do is update the current URL ({}, null, strNewPath) is all you need to do. Best to test first with if (history.pushState) {} – Craig Jacobs
upvote
  flag
Yes its working. no matter if use something like this. var variable='abc' and then you use window.history.pushState(variable, 'Title', '/page2.php'); thanks. – Umar Asghar
1 upvote
  flag
you can just enter null for the first 2 parameters if you dont want to change them. You can also use an absolute url for the third parameter. – Andrew
1 upvote
  flag
It would be nice if you put some more information just IN the answer. I don't have idea, what parameter 1 does. – Soaku

If what you're trying to do is allow users to bookmark/share pages, and you don't need it to be exactly the right URL, and you're not using hash anchors for anything else, then you can do this in two parts; you use the location.hash discussed above, and then implement a check on the home page, to look for a URL with a hash anchor in it, and redirect you to the subsequent result.

For instance:

1) User is on www.site.com/section/page/4

2) User does some action which changes the URL to www.site.com/#/section/page/6 (with the hash). Say you've loaded the correct content for page 6 into the page, so apart from the hash the user is not too disturbed.

3) User passes this URL on to someone else, or bookmarks it

4) Someone else, or the same user at a later date, goes to www.site.com/#/section/page/6

5) Code on www.site.com/ redirects the user to www.site.com/section/page/6, using something like this:

if (window.location.hash.length > 0){ 
   window.location = window.location.hash.substring(1);
}

Hope that makes sense! It's a useful approach for some situations.

It's possible without using hashes, have a look to the asual jQuery Address plugin:

Example here.

Note that it will use hashes in IE, there is no workaround for it.

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.

The HTML5 replaceState is the answer, as already mentioned by Vivart and geo1701. However it is not supported in all browsers/versions. History.js wraps HTML5 state features and provides additional support for HTML4 browsers.

As pointed out by Thomas Stjernegaard Jeppesen, you could use History.js to modify URL parameters whilst the user navigates through your Ajax links and apps.

Almost an year has passed since that answer, and History.js grew and became more stable and cross-browser. Now it can be used to manage history states in HTML5-compliant as well as in many HTML4-only browsers. In this demo You can see an example of how it works (as well as being able to try its functionalities and limits.

Should you need any help in how to use and implement this library, i suggest you to take a look at the source code of the demo page: you will see it's very easy to do.

Finally, for a comprehensive explanation of what can be the issues about using hashes (and hashbangs), check out this link by Benjamin Lupton.

Before HTML5 we can use:

parent.location.hash = "hello";

and:

window.location.replace("http:www.example.com");

This method will reload your page, but HTML5 introduced the history.pushState(page, caption, replace_url) that should not reload your page.

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

history.pushState({}, null, newUrl);
1 upvote
  flag
Best to test first with if (history.pushState) {} Just in case old browser. – Craig Jacobs
upvote
  flag
This doesn't work any more you will get in Firefox: The operation is insecure. – kkatusic

Use history.pushState() from HTML 5 History API

refer link for more details HTML5 History API

Below is the function to change the URL without reloading the page. It only support for HTML5

  function ChangeUrl(page, url) {
        if (typeof (history.pushState) != "undefined") {
            var obj = {Page: page, Url: url};
            history.pushState(obj, obj.Page, obj.Url);
        } else {
            window.location.href = "homePage";
            // alert("Browser does not support HTML5.");
        }
    }

  ChangeUrl('Page1', 'homePage');
4 upvote
  flag
What is page? – Green
1 upvote
  flag
@Green, page is a short title for the state to which you're moving. Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. From: developer.mozilla.org/en-US/docs/Web/API/… – Snook

In modern browsers and HTML5, there is a method called pushState on on window history. That will change the URL and push it to the history without loading the page.

You can use it like this, it will take 3 parameters, 1) state object 2) title and a URL):

window.history.pushState({page: "another"}, "another page", "example.html");

This will change the url, but not reload the page, also doesn't check if the page exist, so if you some javascript code which be reacting to the URL, you can work with them like this.

Also there is history.replaceState() which does exactly the same thing, except it will modify the current history instead of creating a new one!

Also you can create a function to check if history.pushState exist, then carry on with the rest like this:

function goTo(page, title, url) {
  if ("undefined" !== typeof history.pushState) {
    history.pushState({page: page}, title, url);
  } else {
    window.location.assign(url);   
  }
}

goTo("another page", "example", 'example.html');

Also you can change the # for <HTML5 browsers, which won't reload the page, that's the way Angular use to do SPA according to hashtag...

Changing # is quite easy, doing like:

window.location.hash = "example";

and you can detect it like this:

window.onhashchange = function () {
  console.log("#changed", window.location.hash);
}

Use window.history.pushState("object or string", "Title", "/new-url"), but it's still send new url request to server

8 upvote
  flag
A quick search shows pushState has been mentioned only 14 times in other answers! – Nathan Tuggy

Not the answer you're looking for? Browse other questions tagged or ask your own question.