Update URL of browser without page reload

When you are working client side (Browser) then sometimes you change the content of browser or view, and then you need to update the URL of the browser so that when user refreshes or reload the page then the same thing can be visible. 

window.history have different functions to update or switch the states of the browser. It has the following functions:

window.history.go(-1);  // For back navigation

window.history.go(1);   // For forward navigation

let entries = window.history.length; // Get the history size

let stateObject = { foo: "bar" };
history.pushState(stateObject, "page 2", "newpage.html"); // Add new the browser state

Let us breaf about pushState.

pushState() takes three parameters:

1. State object

2. Title

3. URL (optional)

1. State: This is an object that can contain any data or information related to the page like User Information, Product information etc. It has a limit of data to 640k. So good practice is to store data in the state in JSON format.

2. Title: This is the title of the page. Firefox is ignoring this parameter. So it will go good to pass it blank.

3. URL: This parameter is used to provide new history entry to the browser. If your browser reloads then this URL will be call and will display in the address bar.

 

In some cases, you need to update the current state without adding in the browser history. Then you can use replaceState function.

history.replaceState(stateObj, "newpage", "xyz.html");

 

let currentState = history.state; // Get the current state values

 

 

Keywords: