The sessionStorage feature in JavaScript is a part of the window object available in all up-to-date web browsers. It stores information linked to the page's protocol, hostname, and port. Each window possesses its own sessionStorage, allowing for the reliable storage of user data.
When working with JavaScript, the method used to retrieve elements stored within the session storage attribute is getItem. This method is available within the storage object, which can either be a JavaScript session Storage object or a local Storage object.
Methods of the JavaScript sessionStorage
To get an element from javascript sessionStorage, we must first make an element and keep the element in session storage. We can get it back at a later time. The storage object has four methods: setItem, getItem, removeItem, and clear.
- setItem: it works to set the information for the session storage element.
- getItem: it is worked for retrieving and displaying the session storage element.
- removeItem: it displays to delete a specific session storage element.
- key: it works to get the name of the data in the session storage position.
- clear: it is displayed to remove or clear entire items of the session storage element.
Why sessionStorage in JavaScript
The sessionStorage can be used in many different ways. And here are the most important ones:
- The interface of the webpage can be saved in the sessionStorage.
- When the user returns to the page later, you can use the sessionStorage to bring back the saved user interface.
- We can also use sessionStorage to transmit data among pages rather than using invisible input fields or URL parameters.
Syntaxes
Below are examples demonstrating the usage of the set item method in JavaScript's session storage:
- The syntax depicts the utilization of the set item method within JavaScript's session storage.
The structure demonstrates the usage of the displayItem function in JavaScript for session storage.
sessionStorage.getItem('name');
- The syntax demonstrates the usage of the removeItem method in JavaScript's sessionStorage.
- The provided syntax demonstrates the usage of the clear method in JavaScript for the sessionStorage object.
sessionStorage.removeItem('name');
sessionStorage.clear();
Operating data in the JavaScript sessionStorage
1) Using sessionStorage
Access the sessionStorage by utilizing the window.sessionStorage property within the window object.
Accessing the sessionStorage can be conveniently achieved by utilizing the provided syntax, as the global object in this case is the window.
window.sessionStorage
sessionStorage
2) Data storage in the sessionStorage
To store a name-value pair in the sessionStorage, you can achieve it by performing the steps below:
sessionStorage.setItem('name','Example');
When the sessionStorage includes an item with the same name as the variable, the setItem function is used to update the value of that item to "C# Tutorial". If the item does not exist, a new item will be added to the sessionStorage.
3) Obtaining information from sessionStorage
The method getItem is capable of fetching the value of an item based on its name. In the following example, the values of the item "name" are retrieved.
const name = sessionStorage.getItem(' name');
console.log(name);
If the name variable does not correspond to any items, the getItem method may return null.
4) Eliminating an item by name
Utilize the removeItem function to eliminate an item based on its name. The object identified by the name "name" can be deleted using the following method:
sessionStorage.removeItem('name');
5) Repeating step 5 for each item
To loop through each item in the sessionStorage, you should adhere to the following guidelines:
- Utilize the object.keys method to fetch all keys from the sessionStorage object.
- Use a for...of loop to access the elements using keys and iterate through them.
The stages are shown in the code below:
let key_var = Object.keys(sessionStorage);
for(let key_data of key_var) {
console.log(`${key_data}: ${sessionStorage.getItem(key_data)}`);
}
6) Clearing all data stored in the sessionStorage.
Upon closing the tab or window of the web browser, any data stored in the sessionStorage is promptly removed.
Furthermore, you have the capability to remove all data stored in the sessionStorage programmatically by employing the clear method.
sessionStorage.clear();
Examples
Below are some instances that demonstrate the utilization of JavaScript's sessionStorage using various approaches.
Example 1
The following example illustrates the usage of the setItem and getItem methods in JavaScript's sessionStorage. By utilizing a sessionStorage object, it is possible to establish an array and store data within it. Subsequently, the getItem method can be employed with the object to retrieve and present the stored information.
<html>
<head>
<title> Display data using sessionStorage in JavaScript </title>
</head>
<body style = "text-align: center;">
<h4> Display data using sessionStorage in JavaScript </h4>
<p id = "retrive"></p>
<p id = "retrive1"></p>
<script>
const Student = {
name: 'Ram',
Roll_no : 37,
website : 'Example',
learn : 'online mode',
age: 19,
subject: 'Javascript'
}
const Tutorial = {
subject: 'Javascript',
website : 'Example',
mode : 'online',
cost : 'Free',
user : 'student and fresher'
}
sessionStorage.setItem("Student", JSON.stringify(Student));
var Data = sessionStorage.getItem('Student');
document.getElementById('retrive').innerHTML = Data;
sessionStorage.setItem("Tutorial", JSON.stringify(Tutorial));
var Data_Tutorial = sessionStorage.getItem('Tutorial ');
document.getElementById('retrive1').innerHTML = Data_Tutorial;
</script>
</body>
</html>
Output
The image displays the values of items set in the session storage object.
Example 2
The following demonstration illustrates the utilization of session storage in JavaScript using the set and get item methods. By employing the getItem method with the object, it allows for the presentation of date and time details. While the array value is managed through the get and set methods, the date value is assigned data explicitly.
<html>
<head>
<title> Display data using sessionStorage in JavaScript </title>
</head>
<body style = "text-align: center;">
<h4> Display data using sessionStorage in JavaScript </h4>
<p id = "retrive"></p>
<p id = "retrive1"></p>
<script>
const Student = {
name: 'Ram',
Roll_no : 37,
website : 'Example',
learn : 'online mode',
age: 19,
subject: 'Javascript'
}
sessionStorage.setItem("Student", JSON.stringify(Student));
var Data = sessionStorage.getItem('Student');
document.getElementById('retrive').innerHTML = Data;
let datetime = new Date();
sessionStorage.current_time = datetime;
var data_date = sessionStorage.getItem('current_time');
document.getElementById('retrive1').innerHTML = data_date;
</script>
</body>
</html>
Output
The image illustrates the retrieval of item keys and their corresponding values from the session storage object, presenting them as an output.
Example 3
In this instance, we demonstrate the utilization of the remove items method in JavaScript's sessionStorage. By employing the setItem function, we can retrieve the object and exhibit the data stored within. The removeItem(data) function is utilized to eliminate a specific item from the JavaScript sessionStorage.
<html>
<head>
<title> Display data using sessionStorage in JavaScript </title>
</head>
<body style = "text-align: center;">
<h4> Display data using sessionStorage in JavaScript </h4>
<p id = "retrive"></p>
<p id = "retrive1"></p>
<p id = "Studentresult"></p>
<script>
const Student = {
name: 'Ram',
Roll_no : 37,
website : 'Example',
learn : 'online mode',
age: 19,
subject: 'Javascript'
}
sessionStorage.setItem("Student", JSON.stringify(Student));
var Data = sessionStorage.getItem('Student');
document.getElementById('retrive').innerHTML = Data;
let datetime = new Date();
sessionStorage.current_time = datetime;
var data_date = sessionStorage.getItem('current_time');
document.getElementById('retrive1').innerHTML = data_date;
sessionStorage.def_storage_type = 'Session storage'
sessionStorage.setItem("Student", JSON.stringify(Student));
document.getElementById('Studentresult').innerHTML = 'sessionStorage.getItem("Student") : ' + sessionStorage.getItem("Student") +'<br/>' + "sessionStorage.getItem('def_storage_type') : " + sessionStorage.getItem('def_storage_type') +'<br/>';
sessionStorage.removeItem('def_storage_type');
document.getElementById('Studentresult').innerHTML += '<br/>' + 'After Removing the item def_storage_type: ' +'<br/>' + "sessionStorage.getItem('def_storage_type') : " + sessionStorage.getItem('def_storage_type') +'<br/>';
document.getElementById('Studentresult').innerHTML += '<br/>' +"sessionStorage.getItem('data') : " + sessionStorage.getItem('def_storage_type');
</script>
</body>
</html>
Output
The image illustrates the deleted item and the values stored in the session storage object, presenting it as the output.
Example 4
The demonstration illustrates the utilization of the JavaScript sessionStorage alongside the removeItem method. By employing the get and set methods, we can retrieve the object and exhibit the associated details. The clear function is utilized to eliminate and clear the specified item within the JavaScript sessionStorage. Consequently, the output will display null as the value.
<html>
<head>
<title> Clear the session using sessionStorage in JavaScript </title>
</head>
<body style = "text-align: center;">
<h4> Clear the session using the sessionStorage object in JavaScript </h4>
<p id = "Studentresult"></p>
<script>
const Student = {
name: 'Ram',
Roll_no : 37,
website : 'Example',
learn : 'online mode',
age: 19,
subject: 'Javascript'
}
sessionStorage.def_storage_type = 'Session storage'
sessionStorage.setItem("Student", JSON.stringify(Student));
document.getElementById('Studentresult').innerHTML = 'sessionStorage.getItem("Student") : ' + sessionStorage.getItem("Student") +'<br/>' + "sessionStorage.getItem('def_storage_type') : " + sessionStorage.getItem('def_storage_type') +'<br/>';
sessionStorage.clear();
document.getElementById('Studentresult').innerHTML += '<br/>' + 'After clearing the session of the def_storage_type: ' +'<br/>' + "sessionStorage.getItem('def_storage_type') : " + sessionStorage.getItem('def_storage_type') +'<br/>';
document.getElementById('Studentresult').innerHTML += '<br/>' +"sessionStorage.getItem('data') : " + sessionStorage.getItem('def_storage_type');
</script>
</body>
</html>
Output
The image illustrates the session storage object in a transparent manner, presenting it as an output.
Example 5
The following example demonstrates the utilization of the session storage feature in JavaScript, showcasing the methods for retrieving, storing, and presenting items. The primary objective is to exhibit all stored objects within the JavaScript session storage. The key technique involves displaying pertinent information, achieved by utilizing the setItem method.
<html>
<head>
<title> Display data using sessionStorage in JavaScript </title>
</head>
<body style = "text-align: center;">
<h4> Display data using sessionStorage in JavaScript </h4>
<p id = "retrive"></p>
<p id = "retrive1"></p>
<script>
const Student = {
name: 'Ram',
Roll_no: 37,
website : 'Example',
learn : 'online mode',
age: 19,
subject: 'Javascript'
}
const Tutorial = {
subject: 'Javascript',
website : 'Example',
mode : 'online',
cost : 'Free',
user : 'student and fresher'
}
sessionStorage.setItem("Student", JSON.stringify(Student));
sessionStorage.setItem("Tutorial", JSON.stringify(Tutorial));
let datetime = new Date();
sessionStorage.current_time = datetime;
var data_date = sessionStorage.getItem('current_time');
let key_var = Object.keys(sessionStorage);
for(let key_data of key_var) {
console.log(`${key_data}: ${sessionStorage.getItem(key_data)}`);
}
</script>
</body>
</html>
Output
The image illustrates the full details of the session storage object and presents it as an output for reference.
Example 6
The illustration demonstrates an alternative approach in JavaScript for utilizing session storage to retrieve and exhibit data. The code snippet showcases the initialization function, which enables the display of a dark mode background using the stored information. Conversely, it allows the utilization of a light mode, presenting a webpage with a white or light-colored background.
<html>
<head>
<title> Display data using sessionStorage in JavaScript </title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-size: 18px;
background-color: white;
color: black;
line-height: 1.9;
transition: 0.3s ease-in-out;
padding: 15px;
}
.dark {
background-color: black;
color: white;
}
</style>
</head>
<body style = "text-align: center;">
<h4> Display data using sessionStorage in JavaScript </h4>
<p id = "retrive"> we can see the dark mode on the web page. </p>
<p id = "retrive1"></p>
<a id="mode_switcher" class="btn"></a>
<script>
const MOON_VAR = '?';
const SUN_VAR = '??';
const DARK_MODE_DISPLAY = 'dark';
const LIGHT_MODE_DISPLAY = 'light';
const DEFAULT_MODE_DISPLAY = DARK_MODE_DISPLAY;
const btn = document.querySelector('#mode_switcher');
init();
function init() {
let storedMode_display = sessionStorage.getItem('mode_display');
if (!storedMode_display) {
storedMode_display = DEFAULT_MODE_DISPLAY;
sessionStorage.setItem('mode_display', DEFAULT_MODE_DISPLAY);
}
setMode_display(storedMode_display);
}
function setMode_display(mode_display = DEFAULT_MODE_DISPLAY) {
if (mode_display === DARK_MODE_DISPLAY) {
btn.textContent = MOON_VAR;
document.body.classList.add(DARK_MODE_DISPLAY);
} else if (mode_display === LIGHT_MODE_DISPLAY) {
btn.textContent = SUN_VAR;
document.body.classList.remove(DARK_MODE_DISPLAY);
}
}
btn.addEventListener('click', function () {
let mode_display = sessionStorage.getItem('mode_display');
if (mode_display) {
let newMode_display = mode_display == DARK_MODE_DISPLAY ? LIGHT_MODE_DISPLAY : DARK_MODE_DISPLAY;
setMode_display(newMode_display);
sessionStorage.setItem('mode_display', newMode_display);
}
});
</script>
</body>
</html>
Output
The image depicts the details of the session storage object, showcasing the mode and display as the output.
Conclusion
Data can be stored exclusively for a session through the use of sessionStorage. When you close a browser tab or window, the data stored in the sessionStorage will be deleted by the browser.
As the sessionStorage is considered an object within the Storage system, it allows for the manipulation of data within it through the methods available in the Storage type.