Chapter 10: HTML Web Storage (LocalStorage & SessionStorage)
10.1 Introduction to Web Storage
Web Storage provides a way to store key-value pairs in a web browser. Unlike cookies, Web Storage is more secure and can store larger amounts of data.
There are two types of Web Storage:
- LocalStorage: Stores data with no expiration date. Even if the browser is closed, the data remains.
- SessionStorage: Stores data only for the session. The data is removed once the browser is closed.
10.2 LocalStorage
LocalStorage allows data to persist across browser sessions.
Example: Storing and Retrieving Data
<input type="text" id="name" placeholder="Enter your name"> <button onclick="saveData()">Save</button> <button onclick="loadData()">Load</button> <p id="output"></p> <script> function saveData() { let name = document.getElementById("name").value; localStorage.setItem("username", name); alert("Data saved!"); } function loadData() { let storedName = localStorage.getItem("username"); if (storedName) { document.getElementById("output").innerText = "Stored Name: " + storedName; } else { document.getElementById("output").innerText = "No data found."; } } </script>
10.3 SessionStorage
SessionStorage only stores data for the duration of a session (i.e., until the browser is closed).
Example: Using SessionStorage
<input type="text" id="sessionName" placeholder="Enter session data"> <button onclick="saveSessionData()">Save Session Data</button> <button onclick="loadSessionData()">Load Session Data</button> <p id="sessionOutput"></p> <script> function saveSessionData() { let sessionData = document.getElementById("sessionName").value; sessionStorage.setItem("sessionKey", sessionData); alert("Session data saved!"); } function loadSessionData() { let sessionValue = sessionStorage.getItem("sessionKey"); if (sessionValue) { document.getElementById("sessionOutput").innerText = "Session Data: " + sessionValue; } else { document.getElementById("sessionOutput").innerText = "No session data found."; } } </script>
10.4 Clearing Storage
You can remove specific items or clear all stored data.
Example: Clearing Data
<button onclick="clearLocalStorage()">Clear LocalStorage</button> <button onclick="clearSessionStorage()">Clear SessionStorage</button> <script> function clearLocalStorage() { localStorage.clear(); alert("LocalStorage cleared!"); } function clearSessionStorage() { sessionStorage.clear(); alert("SessionStorage cleared!"); } </script>
10.5 Summary
In this chapter, we covered:
- Understanding Web Storage and its advantages over cookies
- Using LocalStorage to persist data across sessions
- Using SessionStorage for temporary data storage
- Clearing stored data