How to Modify the URL without reloading the page?
- Updating address bar with new URL without hash or reloading the page
- we can then use window.onpopstate to detect the back/forward button navigation:
- This works in Chrome, Safari, FF4+, and IE10pp4+!
We can do this to modify the url,
- use history.pushState like this:
- The problem can be solved by implementing the History API, especially by using the pushState() method.
- We are recommend reading about it in MDN.
- There’s also an all-in-one solution called History.js, it will be implemented in x-browser easily (It will fallback to URL hashes # if the browser doesn’t support it).
Here’s an example:
- The HTML Markup consists of 3 buttons which make a call to a function ChangeUrl.
- This function accepts the page Title and URL as parameters.
- It first checks whether browser supports HTML5 and then a State object containing the page Title and URL is created and is passed to the HTML5 History pushState method along with the page Title and URL as the other two parameters.
The following example adds a query parameter to the URL without refreshing the page but only works on modern HTML5 browsers.
We can use the following:
- Changing only what’s after hash – old browsers
- The above will add a new entry to the history so we can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use.
Below is the function to change the URL without reloading the page. It only support for HTML5