View video tutorial
HTML Session Storage
HTML
The sessionStorage object is used to temporarily store data.
Session Storage
Session Storage uses a sessionStorage object to store data on a temporary basis for a single browser window or tab.
Data disappears at the end of the session, ie when the user closes that browser window or tab.
Session Storage important methods
sessionStorage.setItem(key, value) saves the value associated with a key.
sessionStorage.getItem(key) retrieves values associated with the key.
sessionStorage.removeItem(key) removes the value associated with the key.
sessionStorage.clear() removes all key / value pairs from localStorage.
Learning with HTML Editor "Try it Now"
You can edit the HTML code and view the result using online editor.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Session Storage Example</title>
<meta charset="utf-8" />
<style>
button {
width: 150px;
height: 50px;
background-color: cornflowerblue;
font-size: 14pt;
color: white;
border-radius: 10px;
}
button:hover {
background-color: rgb(17, 87, 218);
color: white;
}
</style>
<script>
// Check if the sessionStorage object exists
function store() {
if (sessionStorage) {
// Store data
sessionStorage.setItem("name", "w3context");
// Retrieve data
alert("Hello, " + sessionStorage.getItem("name"));
} else {
alert("Sorry, this browser do not support local storage.");
}
}
function show() {
if (sessionStorage) {
// Retrieve data
alert("Hello, " + sessionStorage.getItem("name"));
} else {
alert("Sorry, this browser do not support local storage.");
}
}
function remove() {
if (sessionStorage) {
// remove data
sessionStorage.removeItem("name");
alert("data removed");
} else {
alert("Sorry, this browser do not support local storage.");
}
}
function cleared() {
if (sessionStorage) {
// clear data
sessionStorage.clear();
alert("All data cleared");
} else {
alert("Sorry, this browser do not support local storage.");
}
}
</script>
</head>
<body>
<h2>HTML Session Storage Example</h2>
<p>Click this button to trigger a function.</p>
<button onclick="store()">Store</button>
<button onclick="remove()">Remove</button>
<button onclick="cleared()">Clear</button>
<button onclick="show()">Show</button>
</body>
</html>
Click on the "Try it Now" button to see how it works.