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
HTML5 introduced the
history.pushState()
andhistory.replaceState()
methods, which allow you to add and modify history entries, respectively.Read more about this from here
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:
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.
In modern browsers and HTML5, there is a method called
pushState
on windowhistory
. 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):
This will change the url, but not reload the page, also doesn't check if the page exist, so if you do 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:
Also you can change the
#
for<HTML5 browsers
, which won't reload the page, that's the wayAngular
use to doSPA
according to hashtag...Changing
#
is quite easy, doing like:and you can detect it like this:
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.
Any changes of the loction (either
window.location
ordocument.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.
You can see here Update URL of browser without page reload