Page 1 of 1

Change the URL address without reloading the page

Posted: 08 Jan 2015, 08:28
by MarPlo
Is there any way I can modify the URL of the current page without reloading the page?
I only need to change the portion after the domain, when a button is clicked and a new content is added with ajax.
I tryed this code, but it reloads the page:

Code: Select all

window.location.href = 'coursesweb.net/page2.htm';
How can i change the URL without page refresh?

Change the URL address without reloading the page

Posted: 08 Jan 2015, 09:08
by Admin
You can use the history.pushState() method to change the url address without refreshing the page.
It works in modern browsers which suport HTML5.
pushState adds an entry to the history object. Try this code, click on the button and then use your browsers back button.

Code: Select all

<button id="btn">CLICK</button>
<script>
// when click on #btn, modify url without refreshing page
document.getElementById('btn').addEventListener('click', function(){
  history.pushState(null, 'A new title', 'page_2.htm');
});
</script>
The pushState(State, Title, Url) takes 3 arguments;
- State - an Object or a String, will stay with each state, so if you go back in the history, you’ll get the object /string for that state.
- Title - a string used as an internal reference to the title of the new page.
- Url - a string with the new url to be added into the address bar. The url must be relative, or at least have the same origin as the current url.

The browser won‘t try to get the new url and it doesn’t matter if it doesn't exist on the server.

- Demo:
Click on this button and see the result in the browser address-bar.