Home ยป HTML5 Web Storage Tutorial

HTML5 Web Storage Tutorial

by shedders

HTML5 Web Storage provides a way to store data in the browser without requiring cookies.

It offers two storage options: localStorage and sessionStorage, each with unique characteristics and use cases.

In this tutorial, you’ll learn:

  1. What Web Storage is.
  2. Differences between localStorage and sessionStorage.
  3. How to use Web Storage with examples.
  4. Practical examples of using Web Storage for web development.

1. What is Web Storage?

Web Storage is a mechanism for storing key-value pairs in a web browser. It is more secure, faster, and larger in storage capacity compared to cookies.

Key Points:

  • localStorage: Data persists even after the browser is closed.
  • sessionStorage: Data persists only for the session (until the browser tab is closed).

2. Differences Between localStorage and sessionStorage

Feature localStorage sessionStorage
Persistence Data persists indefinitely. Data persists until the tab is closed.
Scope Accessible across browser tabs and windows. Accessible only in the same tab.
Storage Limit 5MB per origin (varies by browser). 5MB per origin (varies by browser).
Use Case Storing long-term data (e.g., user preferences). Temporary data (e.g., form data).

3. How to Use Web Storage

3.1 Storing Data

Data is stored as key-value pairs in the Web Storage APIs.

// Storing data in localStorage
localStorage.setItem("username", "JohnDoe");

// Storing data in sessionStorage
sessionStorage.setItem("sessionID", "12345");

3.2 Retrieving Data

Retrieve stored data using the key.

// Retrieving data from localStorage
let username = localStorage.getItem("username");
console.log(username); // Output: JohnDoe

// Retrieving data from sessionStorage
let sessionID = sessionStorage.getItem("sessionID");
console.log(sessionID); // Output: 12345

3.3 Removing Data

You can remove specific items or clear all stored data.

// Removing a specific item
localStorage.removeItem("username");

// Clearing all localStorage data
localStorage.clear();

// Removing a specific item from sessionStorage
sessionStorage.removeItem("sessionID");

// Clearing all sessionStorage data
sessionStorage.clear();

4. Practical Examples

Example 1: Storing User Preferences with localStorage

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Store User Preferences</title>
</head>
<body>
    <h1>Choose Your Theme</h1>
    <button id="darkTheme">Dark Theme</button>
    <button id="lightTheme">Light Theme</button>

    <script>
        // Apply the stored theme on page load
        const theme = localStorage.getItem("theme");
        if (theme) {
            document.body.style.backgroundColor = theme === "dark" ? "black" : "white";
            document.body.style.color = theme === "dark" ? "white" : "black";
        }

        // Set the theme and store it in localStorage
        document.getElementById("darkTheme").onclick = () => {
            document.body.style.backgroundColor = "black";
            document.body.style.color = "white";
            localStorage.setItem("theme", "dark");
        };

        document.getElementById("lightTheme").onclick = () => {
            document.body.style.backgroundColor = "white";
            document.body.style.color = "black";
            localStorage.setItem("theme", "light");
        };
    </script>
</body>
</html>

Explanation:

  • User selects a theme (dark or light).
  • The choice is saved in localStorage and applied on subsequent visits.

Example 2: Saving Form Data with sessionStorage

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Autosave</title>
</head>
<body>
    <h1>Form Autosave</h1>
    <form id="userForm">
        <label for="name">Name:</label>
        <input type="text" id="name" placeholder="Enter your name"><br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" placeholder="Enter your email"><br><br>
        <button type="submit">Submit</button>
    </form>

    <script>
        // Restore form data on page load
        document.getElementById("name").value = sessionStorage.getItem("name") || "";
        document.getElementById("email").value = sessionStorage.getItem("email") || "";

        // Save form data in sessionStorage
        document.getElementById("name").oninput = (e) => {
            sessionStorage.setItem("name", e.target.value);
        };

        document.getElementById("email").oninput = (e) => {
            sessionStorage.setItem("email", e.target.value);
        };
    </script>
</body>
</html>

Explanation:

  • The form inputs are saved in sessionStorage as the user types.
  • Data persists within the same tab session and is restored if the page is refreshed.

Example 3: Tracking Page Views with localStorage

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Views Counter</title>
</head>
<body>
    <h1>Welcome!</h1>
    <p>You have visited this page <span id="viewCount"></span> times.</p>

    <script>
        // Get the current view count from localStorage
        let views = parseInt(localStorage.getItem("views")) || 0;

        // Increment the view count and update localStorage
        views += 1;
        localStorage.setItem("views", views);

        // Display the view count
        document.getElementById("viewCount").textContent = views;
    </script>
</body>
</html>

Explanation:

  • Each page visit increments a counter stored in localStorage.
  • The counter persists across browser sessions.

Example 4: Clearing User Data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clear User Data</title>
</head>
<body>
    <h1>Manage Your Data</h1>
    <button id="clearData">Clear All Data</button>

    <script>
        document.getElementById("clearData").onclick = () => {
            localStorage.clear();
            sessionStorage.clear();
            alert("All data cleared!");
        };
    </script>
</body>
</html>

Explanation:

  • Clicking the button clears all stored data from both localStorage and sessionStorage.

5. Browser Support

Web Storage is supported by all modern browsers, including:

  • Google Chrome
  • Mozilla Firefox
  • Microsoft Edge
  • Safari

Ensure compatibility for older browsers by checking for storage availability:

if (typeof(Storage) !== "undefined") {
    console.log("Web Storage is supported.");
} else {
    console.log("Web Storage is not supported.");
}

6. Best Practices

  1. Avoid Sensitive Data: Never store sensitive information like passwords in Web Storage.
  2. Limit Usage: Use Web Storage for small amounts of data (e.g., user preferences).
  3. Clean Up: Remove unnecessary items to prevent bloating the storage.
  4. Data Validation: Validate data before using it to avoid unexpected issues.

Conclusion

In this tutorial, you learned:

  1. The difference between localStorage and sessionStorage.
  2. How to store, retrieve, and remove data.
  3. Practical use cases for Web Storage, including user preferences and form autosaving.

Experiment with these examples and integrate Web Storage into your projects to enhance user experience

You may also like