Update URL of browser without page reload

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

window.history have different functions to update or switch the states of browser. It have 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 a object that can contain any data or information related to page like User Information, Product information etc. It has limit of data to 640k. So good practice is to store data in state in JSON format.

2. Title: This is the title of 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 reload then this URL will be call and will display in addressbar.

 

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: