It would also be nice if the back button would reload the original URL.
With HTML 5, use the
history.pushState function. As an example:
and a href:
<a href="#" id='click'>Click to change url to bar.html</a>
If you want to change the URL without adding an entry to the back button list, use
If you want it to work in browsers that don’t support
history.popState yet, the “old” way is to set the fragment identifier, which won’t cause a page reload.
The basic idea is to set the
window.location.hash property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don’t support
onhashchange (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using
setInterval for example) and update the page. You will also need to check the hash value on page load to set up the initial content.
If you’re using jQuery there’s a hashchange plugin that will use whichever method the browser supports. I’m sure there are plugins for other libraries as well.
One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.
I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches…
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]
window.location.href contains the current URL. You can read from it, you can append to it, and you can replace it, which may cause a page reload.
If you use a ? instead of a #, you will force a reload of the page, but since you will parse the saved state on load this may not actually be a problem; and this will make the forward and back buttons work correctly as well.