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
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 towww.site.com/section/page/6
, using something like this:Hope that makes sense! It's a useful approach for some situations.
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:
You can then use
window.onpopstate
to detect the back/forward button navigation:For a more in-depth look at manipulating browser history see this MDN article.
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 saywww.mybank.com
. The user will be totally unaware that they are really looking atwww.mysite.com
.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.
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.