Definition and Usage
- The localStorage and sessionStorage properties allow to save key/value pairs in a web browser.
- The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).
- Tip: Also look at the localStorage property which stores data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
Syntax
window.sessionStorage
Syntax for SAVING data to sessionStorage:
sessionStorage.setItem("key", "value");
Syntax for READING data from sessionStorage:
var lastname = sessionStorage.getItem("key");
Syntax for REMOVING saved data from sessionStorage:
sessionStorage.removeItem("key");
Syntax for REMOVING ALL saved data from sessionStorage:
sessionStorage.clear();
Technical Details
Return Value: A Storage objectExample
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
sessionStorage.setItem("lastname", "Smith");
// Retrieve
var lastName = sessionStorage.getItem("lastname");
console.log(lastName ); //Output: Smith
} else {
var error = "Sorry, your browser does not support Web Storage...";
console.log(error);
}
</script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
sessionStorage.setItem("lastname", "Smith");
// Retrieve
var lastName = sessionStorage.getItem("lastname");
console.log(lastName ); //Output: Smith
} else {
var error = "Sorry, your browser does not support Web Storage...";
console.log(error);
}
</script>
Comments
Post a Comment