How can I change the current URL?
document.location.href = newUrl;
https://developer.mozilla.org/en-US/docs/Web/API/document.location
Simple assigning to window.location
or window.location.href
should be fine:
window.location = newUrl;
However, your new URL will cause the browser to load the new page, but it sounds like you'd like to modify the URL without leaving the current page. You have two options for this:
Use the URL hash. For example, you can go from
example.com
toexample.com#foo
without loading a new page. You can simply setwindow.location.hash
to make this easy. Then, you should listen to the HTML5hashchange
event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers.You could use HTML5 History to modify the path without reloading the page. This will allow you to change from
example.com/foo
toexample.com/bar
. Using this is easy:window.history.pushState("example.com/foo");
When the user presses "back", you'll receive the window's
popstate
event, which you can easily listen to (jQuery):$(window).bind("popstate", function(e) { alert("location changed"); });
Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.
If you just want to update the relative path you can also do
window.location.pathname = '/relative-link'
"http://domain.com" -> "http://domain.com/relative-link"