How to modify url without reloading the page

There are some ways in latest JavaScript and latest browsers in which you can use modify the url without reloading the page. HTML5 introduced two methods history.pushState() and history.replaceState()

history.pushState()

If you want to add some parameters or add a new url then call the history.pushState() method. Here is example to achieve this-

It accepts 3 parameters: State Object, A title and a URL.

State Object:

This can be anything which is used to save in the browser history entry. It has a size limit of 640k characters.

Page Title:

This parameter is currently ignored. You can pass a blank string at the place of this parameter.

URL:

This is the main parameter which will be used as page url. You can pass any url or append query strings in this parameter. Few examples are shown below:-

Example #1 [change page url]

This is useful when you did login and now you want users to move to dashboard page. The users will now see the dashboard page without reloading the browser. The page history is maintained properly.

Example #2 [append query string]

This example is useful when you don’t want to change the page url but only need to append some query strings in url.

history.replaceState()

This method modifies the current history entry instead of creating a new one. Here is an example of it-

Reference taken from MDN

Leave a Reply

Your email address will not be published. Required fields are marked *