How to use History API on JavaScript
By: Javascript Jeep
Tags: Javascript Tips, Javascript Jeep, JavaScript, Coding, History Api

You can also change the URL of the page using pushState and replaceState method.

PushState

The pushstate will change the URL of the page and add the changed URL to the top of the URL stack of history object.

Syntax

history.pushState(state , title, URI/URL )

The “ state ”is any javascript data which will be stored in history.state member variable, which will be available once you navigate through the page.

The “ title ” on the code is just a text, which has no effect on any browser. You can skip that by passing an empty string "” or some title text is fine.

The “ URI/URL ” is a string which is the new URL to change.

Let’s try it in console, before executing this just check the history.length . Consider you on page www.google.com

history.pushState("temp data", "title", "newurl");

Once you execute the above code in the console, It will change the URL in the address bar of the page as, www.google.com/newurl , also add the URL to the history object. To confirm that you can check history.length , the length will be incremented by 1. Also, you can press the back button it will go back to www.google.com .

In addition to that we can also store the state(data for current page ) for each URL . In our case, you will store the “ temp data ” in history.state member variable, once you come back to this page you can retrieve the data.

For example: history.pushState("temp data 1", "title", "newurl_1"); history.state; //"temp data 1" history.pushState("temp data 2", "title", "newurl_2"); history.state; //"temp data 2" history.back(); history.state // "temp data 1"

Whenever users come back to the page which is added to history through pushState then an event with the name popstate will be triggered by the browser in that event object with state data. For example

Open a new tab go to a webpage, say www.google.com .

Now add a listener for popstate event.

window.addEventListener('popstate', e => console.log(e) );

Now add the pushState

history.pushState({name: "test1"}, "title", "test1");

Once you press the back button, the popstate event will be triggered, in our case we have added a listener, which will print the event data. In the event data we can find the state member variable.

You can also provide a complete URL on the same domain, for example, you’re in twitter.com , you can use URL param as

history.pushState("data", "" , 'https://twitter.com/newurl');

The above code is equal to

history.pushState("data", "" , 'newurl');

You’re not allowed to change the domain/origin. If you’re in google.com and you try like

history.pushState("data", "" , 'https://twitter.com/newurl');

This will throw an exception because the URL has to be of the same domain/origin. The reason behind this exception is, if this is allowed then developers are able to cheat the people to believe that they are on a different website.

Replace State

The replaceState only changes the URL . It doesn’t add URL to the history of URL the stack. You can check that using the history.length

replaceState("temp data", "title", "new_url");

No matter how many times you execute the above code. It will only change the URL . It is similar to pushState , except replaceState don’t add the URL to the history of URLs.

Creating an App using History API

You will create an app , which has

a list of users of male and female members

a select box with the option to show only male or female or both members

on changing the select box, you will change the URL, if you select male, then your URL should be www.temp.com/male, also add the URL to the history

On refreshing the page, based on the URL you need to display the images.

Let’s develop the list and select box in HTML

<select name="" id="selectbox">

<option value="male">Both</option>

<option value="male">Male</option>

<option value="femalt">Female</option>

</select> <ul id="userslist">

<li gender="male">Ram </li>

<li gender="female">Lakshmi</li>

<li gender="female" >Jolie</li>

<li gender="male">John</li>

</ul>

You need to add an event listener to listen for a select-box change, once the select box changes we need to filter the list. This filter function will show or hide members based on the value of the select box. If the select box value is male then the female users in the list should not be displayed.

let selectBox = document.getElementById('selectbox');

let userslist = document.getElementById('userslist'); selectBox.addEventListener('change' , onSelectBoxChange); function onSelectBoxChange(ev) { let val = this.value;

filterList(val); } function filterList(val) { let users = userslist.children; for(let i = 0; i < users.length; i++) { let user = users[i];

let gender = user.getAttribute('gender'); if(gender === val || val === "both") {

user.style.display = ""

} else {

user.style.display = "none"

} }

}

Also, you need to change the URL of the page once the select-box change, for that you need to add pushState on select-box change.

function onSelectBoxChange(ev) { let val = this.value;

filterList(val);

history.pushState({gender: val}, null, val); }

history.pushState({gender: value}, null, value); , this line will change the URL based on the value of the select box. If you select male then the URL will be www.temp.com/male .

You need to add an event listener to detect if the user clicks the back button by using popstate , on popstate the value of state member variable is available, based on that you need to filter the list again.

window.addEventListener('popstate', onPopState); function onPopState(ev) {

let state = ev.state;

filterList(state.gender); // this will filter the list

}

You also need to handle the page refresh, When you refresh the page, the history doesn’t change. If you’re in google.com with history.length value as 1 , when you refresh the page the history object remains the same with the state value, to handle that

$(window).on("load", function() { let gender = history.state ? history.state.gender : "both"; filter(gender); // this will handle page refresh. }

You can improve this app from here. If you find any issue please comment below.

Please Follow Javascript Jeep🚙💨. Visit JavascriptJeep.com

Share by clicking here.