Change browser url in javascript without refreshing the page

0

Changing the browser url in javascript without refreshing the page was not possible until introduction of Html5. Now it is possible to manipulate the browser history in javascript. We have two methods in Html5 to change the browser address without refreshing the page:

1. history.pushState()
2. history.replaceState()

history.pushState()

history.pushState() method creates a new history of the referrer used in the HTTP header for XMLHttpRequest. This means that it will change the url in the browser without refreshing the page but after the browser address is changed if you click back button, you will be redirected to the original old url. Let us say we have a page at our localhost (http://localhost/index.php) and we want to change the url in the browser on button click to (http://localhost/test). The code required to do the above task is given below:

Html:
<input type="button" value="Push State" />
Javascript:
<script type="text/javascript">
function pushState(){
 history.pushState('index.php','Name','test');   // Name is an optional parameter
}
</script>

The above code will replace index.php with test.

history.replaceState()

history.replaceState() works similar to history.pushState() with a minor difference between the two. Unlike history.pushState(), history.replaceState() does not create a new history of the referrer used in the HTTP REQUEST but it modifies the current history. This means that it will change the url in the browser but if click back button, you won’t be redirected to the original url. An example code of history.replaceState() is given below:

Html:
<input type="button" value="Replace State" />
Javascript:
<script type="text/javascript">
function replaceState(){
 history.replaceState('index.php','Name','test');   // Name is optional parameter
}
</script>
Share.

About Author

Leave A Reply