Whenever there are modifications to the history, the task is to uncover the details of those changes. The pushState method has been invoked. This method serves to track changes made to the browser's history. To implement a monkey patch on window.history when the pushState method is utilized.
The function history will subsequently incorporate all of our custom logic, executing each time there is a change made to the browser's history.
In other terms, we can insert a new entry into the session history stack of the web browser by utilizing the history.pushState function.
Syntax
The structure for the pushState function is outlined below:
history.pushState(state, title, [,url]) (state, title, [,url])
The pushState function takes in three arguments:
1) state
A serializable object represents a specific state. A popstate event is triggered each time you move to a different state. Furthermore, the popstate event includes a state attribute that references the state object associated with the history entry.
2) title
At present, most web browsers do not acknowledge this title attribute. Instead, you should use the document.title property to modify the title of the document. In practical scenarios, the title parameter is commonly assigned an empty string.
3) url
The optional URL parameter allows us to define the URL for the new history entry. An exception will be raised by the method if the provided URL does not match the origin of the URL currently in use.
The web browser fails to load the specified address when we assign it. If the user omits the URL, the browser defaults to utilizing the existing URL.
Examples
The subsequent examples illustrate various aspects related to the history.pushState function.
Example 1 :
The following example illustrates the fundamental capabilities of the history.pushState method. In this scenario, we can utilize the current URL of the window's location to retrieve the existing link. By employing the current URL, we can access the data associated with the method.
<!DOCTYPE html>
<html>
<head>
<title> JavaScript history.pushState Event </title>
</head>
<body>
<h2 id = "data"> JavaScript history.pushState Event </h2>
<p> write history.pushState() method in the console and see the output </p>
<script>
//use url of the window's location
const url_data = new URL(window.location);
//set the data in url link
url_data.searchParams.set('get', 'data method');
//get the value with a link
window.history.pushState({}, '', url_data);
</script>
</body>
</html>
Output
The illustration displays the information generated as a result of the history URL.
Example 2
The following example illustrates how the history.pushState function operates. We can utilize a null state, the existing URL, along with an empty parameter.
<!DOCTYPE html>
<html>
<head>
<title> JavaScript history.pushState Event </title>
</head>
<body>
<h2 id = "data"> JavaScript history.pushState Event </h2>
<p> write history.pushState() method in the console and see the output </p>
<script>
//get the value with link
const url_data = new URL(window.location);
history.pushState(null, "", url_data);
</script>
</body>
</html>
Output
The illustration presents the information generated as a result of the history URL.
Example 3
The following example illustrates how the history.pushState method operates. We can retrieve the URL path corresponding to the specified id. When a web page contains a valid id, it can be utilized as a segment of the URL or as a tab.
<html>
<head>
<title> JavaScript history.pushState Event </title>
</head>
<body>
<h2 id = "data"> JavaScript history.pushState Event </h2>
<p> write history.pushState() method in the console and see the output </p>
<script>
//get the value with link
const url_data = new URL(window.location);
const state ={'id':data}
url_data.searchParams.set('get', state);
history.pushState({'id':'data'}, "", url_data);
</script>
</body>
</html>
Output
The illustration displays the information generated from the history URL.
PushState history in JavaScript illustration
We are going to develop a simple application that showcases tabs for React, Vue, and Angular.
When you select a tab, the corresponding content for that item will be shown. Additionally, the URL will be modified through the history API. The pushState method operates in the following manner:
- If you copy the URL that includes the hashtag and access it through an internet browser, the application will retrieve the relevant content.
- Initially, utilize the querySelector method to select the elements associated with the tabs and their corresponding content.
- Next, construct a mapping object that associates the identifier of each tab with its respective URL hash.
- Next, generate a new map called data, which will link an object's tab identifier to it. Among the properties of the object are url and content.
- Fourth, the click event takes place each time a tab (or li elements) is clicked. We'll make use of the event delegation to increase efficiency. We will therefore handle the clicking event on every tab's parent rather than on each individual tab. The if clause makes sure that the event handlermodifies the text and url when the click event happens on each distinct tab. When weclick the tab's content area, nothing happens.
- Fifth, the update function assigns the CSS class to the selected user tab while removing the active class from the active tab. We run the update method and provide the tab id into it inside the event handler.
- We will therefore handle the clicking event on every tab's parent rather than on each individual tab.
- The if clause makes sure that the event handlermodifies the text and url when the click event happens on each distinct tab. When weclick the tab's content area, nothing happens.
- Furthermore, it utilizes the tab id to obtain the corresponding URL and relevant details from the data. The history.pushState function is then used to alter the current URL.
<div class="container">
<div class = "displays">
<ul>
<li class = "active" id = "display1">link</li>
</ul>
<div class = "datash">
content
</div>
</div>
const displays = document.querySelector(".displays");
const datash = document.querySelector(".displays > .datash");
const hashes = new Map([
["#url_link", "display1"],
]);
const data = new Map([
[
"display1",
{
url: "file.html#react",
content:
"content.",
},
],
]);
displays.addEventListener("click", function (event) {
//write condition with update method.
});
history.pushState(null, "", entry.url);
Example
The subsequent illustration demonstrates the utilization of the history.pushState method in conjunction with multiple URL tabs within a unified container. In this case, we establish three distinct tabs, each containing its respective information. When a tab is clicked, the URL reflects the data associated with that particular tab.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" />
<meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
<title>JavaScript History API: pushState() Demo</title>
<style>
:root {
--active-border-color:black;
--bg-color: #f4f4f4;
--text-color: black;
--tab-bg-color: white;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
font-size: 1rem;
background-color: var(--bg-color);
color: var(--text-color);
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
.displays {
display: flex;
flex-direction: column;
min-height: 200px;
background-color: var(--tab-bg-color);
padding: 10px;
border-radius: 5px;
width: 350px;
}
.displays ul {
list-style: none;
display: flex;
justify-content: space-between;
border-radius: 5px;
}
.displays ul li {
width: 100%;
text-align: center;
padding: 5px;
margin-left: 5px;
cursor: pointer;
font-size: 1.1rem;
}
.displays ul li:hover {
border-bottom: solid 2px var(--active-border-color);
}
.displays ul li.active {
border-bottom: solid 2px var(--active-border-color);
font-weight: bold;
}
.displays .datash {
padding: 10px;
margin: 10px auto;
}
</style>
</head>
<body>
<div class = "container">
<div class = "displays">
<ul>
<li class = "active" id = "display1"> Node.Js </li>
<li id = "display2"> JavaScript </li>
<li id = "display3"> Angular.Js </li>
</ul>
<div class = "datash">
A JavaScript library for building user interfaces
</div>
</div>
</div>
<script>
const displays = document.querySelector(".displays");
const datash = document.querySelector(".displays > .datash");
const hashes = new Map([
["#node", "display1"],
["#jst", "display2"],
["#angular", "display3"],
]);
const data = new Map([
[
"display1",
{
url: "file.html#node",
datash:
"Node is a JavaScript library for creating new user interfaces.",
},
],
[
"display2",
{
url: "file.html#jst",
datash: "JavaScript Framework creating web applications.",
},
],
[
"display3",
{
url: "file.html#angular",
datash:
"Angular is a platform for building mobile and desktop applications.",
},
],
]);
displays.addEventListener("click", function (event) {
if (!event.target.id) return;
update(event.target.id);
});
const update = (tabId) => {
// remove the active class of the previously selected tab
const currentTab = displays.querySelector(".active");
if (currentTab.id != tabId) {
currentTab.classList.remove("active");
}
// add active class to the selected tab
const selectedTab = document.getElementById(tabId);
selectedTab.classList.add("active");
const entry = data.get(tabId);
if (entry) {
// update the URL
history.pushState(null, "", entry.url);
// change the content
datash.innerHTML = entry.datash;
}
};
</script>
</body>
</html>
Output
The illustration displays the tab that contains several links pertaining to the history of URLs.
Conclusion
To insert a new entry into the session history stack of the web browser, utilize the history.pushState function.