How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark the new URL is used?
It would also be nice if the back button would reload the original URL.
I am trying to record JavaScript state in the URL.
If you want it to work in browsers that don't support
history.pushState
andhistory.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 supportonhashchange
(IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (usingsetInterval
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.