Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator
url

How to modify the URL in JavaScript without reloading the page

Behzad Ahmad

The session history of the browser is managed by the browser’s history interface. It includes the frame or the page visited in the tab to locate the current page. By using this state, we can modify the URL of the browser tab without reloading the webpage.

There are two methods to modify the URL in JavaScript without reloading the page. These are:

  • The pushState() method.
  • The replaceState() method.

pushState()

The pushState() method is used to pass the properties in the form of parameters to add the new history entry. It is used to modify the current URL with the new given state without having to reload the page.

It has three parameters:

  • data: This is the object to store data related to URL.

  • title: This is the data related to the title of the webpage.

  • URL: This is the new URL.

The new URL is passed in the form of a string to this method.

Let’s have a look at the basic code to understand the use of this method:

Explanation

  • Lines 3–5: We make a heading above the button.

  • Line 7–9: We add the button that will modify the URL upon clicking.

  • Lines 11–18: This is the function used to modify the URL.

replaceState()

The replaceState() method is used to modify the current history entry. It replaces the current history entry with ones that are passed as parameters.

It has three parameters:

  • data: This is the object to store data related to URL.

  • title: This is the data related to the title of the webpage.

  • URL: This is the new URL.

The new URL is passed in the form of a string to this method.

Let’s have a look at the basic code to understand the use of this method:

Explanation

  • Lines 3–5: We make a heading above the button.

  • Line 7–9: We add the button that will modify the URL upon clicking.

  • Lines 11–18: This is the function used to modify the URL.

RELATED TAGS

javascript
communitycreator
url
RELATED COURSES

View all Courses

Keep Exploring