Advance JavaScript (DOM, BOM, Web API) / Web API

Client Storage - Session Storage

⏲️ Session Storage

  • sessionStorage stores data only for the current browser session.

  • Data stays while the tab/window is open and survives page refresh, but:

    • Deleted when the tab/window is closed

    • Not shared across tabs, even if they open the same website

  • Each tab gets its own separate sessionStorage.

  • Data is also protocol-specific (http vs https are treated differently).

📌 Important Notes

  • sessionStorage is not available when running an HTML file locally (without a server).

  • It works the same way as localStorage, but data lasts only for the session.

🔧 sessionStorage Methods

  • setItem(name, value) → save data

  • getItem(name) → read data

  • removeItem(name) → delete one item

  • clear() → delete everything

  • key(index) → get the key name by index


⚡Managing data in the JavaScript sessionStorage

🧪 Accessing the sessionStorage

  • To access the sessionStorage, you use the sessionStorage property of the window object :

window.sessionStorage
  • Since the window is the global object, you can simply access the sessionStorage like this :

sessionStorage

👍 Storing data in the sessionStorage

  • The following stores a name-value pair in the sessionStorage:

sessionStorage.setItem('mode','dark');
  • If the sessionStorage has an item with the name of mode, the setItem() method will update the value for the existing item to dark. Otherwise, it’ll insert a new item.


🪢 Getting data from the sessionStorage

  • To get the value of an item by name, you use the getItem() method. The following example gets the value of the item ‘mode‘ :

const mode = sessionStorage.getItem('mode');
console.log(mode);// 'dark'
  • If there is no item with the name mode, the getItem() method will return null.


❌ Removing an item by a name

  • To remove an item by the name, you use the removeItem() method. The following removes the item with the name of 'mode' :

sessionStorage.removeItem('mode');

🔁 Iterating over all items

  • To iterate over all items stored in the sessionStorage, you follow these steps:

    • Use Object.keys() to get all keys of the sessionStorage object.

    • Use for...of to iterate over the keys and get the items by keys.

  • The following code illustrates the steps :

let keys = Object.keys(sessionStorage);
for(let key of keys) {
  console.log(`${key}: ${sessionStorage.getItem(key)}`);
}

⛔ Deleting all items in the sessionStorage

  • The data stored in the sessionStorage are automatically deleted when the web browser tab/window is closed.

  • In addition, you can use the clear() method to programmatically delete all data stored in the sessionStorage.

sessionStorage.clear();

❓Why JavaScript sessionStorage

The sessionStorage has many practical applications. And the following are the notable ones:

  • The sessionStorage can be used to store the state of the user interface of the web application. Later, when the user comes back to the page, you can restore the user interface stored in the sessionStorage.

  • The sessionStorage can also be used to pass data between pages instead of using the hidden input fields or URL parameters.


📊 localStorage vs Cookies vs sessionStorage

🔢 No.

🧠 Feature

📦 localStorage

🍪 Cookies

🗂️ sessionStorage

1.

Storage Limit

⭐ ~ 5MB

⚠️ ~4KB

⭐ ~ 5MB

2.

Data Sent with Requests

❌ No

✅ Yes (automatically sent to server)

❌ No

3.

Access Control

Client-side JavaScript only

Client-side + Server

Client-side JavaScript only

4.

Expiration

Never expires (unless removed)

Can set expiry date

Expires when tab/window closes

5.

Per Tab or Shared?

Shared across all tabs of same origin

Shared across all tabs

❗ Unique per tab/window

6.

Availability Offline

Yes

Yes

Yes (but session ends when tab closes)

7.

Use Case

Long-term storage (themes, preferences, app data)

Authentication, sessions, tracking, server-related data

Temporary data for a single session/tab (forms, state, steps)


🧩Session Storage application

  • You’ll build a simple web application that allows users to select the mode, either dark or light mode. By default, it has a light mode. And you’ll use the sessionStorage to remember the mode when the page refreshes.

  • If you refresh the page, the mode that you selected will restore since it’s stored in the sessionStorage.

  • However, if you close the tab or window, the page will reset to the dark mode, which is the default mode.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript sessionStorage Demo</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container">
        <h1>JavaScript sessionStorage Demo</h1>
        <p>Click the button to switch to the dark/light mode.</p>
        <p>Refresh the page to check if the mode is saved.</p>
        <a id="theme-switcher" class="btn"></a>
    </div>
    <script src="js/app.js"></script>
</body>

</html>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* Default light mode styles */
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background-color: #fff;
    color: #333;
    transition: all 0.3s ease-in-out;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    text-align: center;
}

/* Dark mode styles */
body.dark {
    background-color: #111;
    color: #f9f9f9;
}

/* Container for content */
.container {
    max-width: 600px;
}

/* Heading style */
.container h1 {
    margin-bottom: 10px;
    font-size: 2rem;
}

/* Paragraph style */
.container p {
    font-size: 1rem;
    line-height: 1.5;
    color: inherit;
}

/* Button style */
.btn {
    display: inline-block;
    margin-top: 20px;
    font-size: 2rem;
    cursor: pointer;
    user-select: none;
    transition: transform 0.2s ease;
}

/* Optional animation on click */
.btn:active {
    transform: scale(1.2);
}
//First, declare two constants that will be used as the butotn’s label
const MOON = '🌙';
const SUN = '☀️';

//Second, declare three constants for the dark, light, and default modes
const DARK_MODE = 'dark';
const LIGHT_MODE = 'light';
const DEFAULT_MODE = DARK_MODE;

//Third, select the button theme-switcher by using the querySelector()
const btn = document.querySelector('#theme-switcher');

init();

//Fifth, define the init() function that will run when the page loads
//use the getItem() method to retrieve the mode stored in the sessionStorage
function init() {
    let storedMode = sessionStorage.getItem('mode');
    if (!storedMode) {
        storedMode = DEFAULT_MODE;
        sessionStorage.setItem('mode', DEFAULT_MODE);
    }
    setMode(storedMode);
}

//Fourth, define a new function setMode() to change the mode
function setMode(mode = DEFAULT_MODE) {
    if (mode === DARK_MODE) {
        btn.textContent = SUN;
        document.body.classList.add(DARK_MODE);

    } else if (mode === LIGHT_MODE) {
        btn.textContent = MOON;
        document.body.classList.remove(DARK_MODE);
    }
}

//Sixth, attach a click event handler to the theme-switcher button
btn.addEventListener('click', function () {
    let mode = sessionStorage.getItem('mode');
    if (mode) {
        let newMode = mode == DARK_MODE ? LIGHT_MODE : DARK_MODE;
        setMode(newMode);
        sessionStorage.setItem('mode', newMode);
    }
});
  • If the sessionStorage doesn’t have the mode item, the init() function will switch the page to the default mode, which is the dark mode. Otherwise, it sets to the mode stored in the sessionStorage.

  • The click event handler gets the mode stored in the sessionStorage.

  • If the mode item exists, it toggles the mode. In other words, the light mode becomes the dark mode and vice versa.

  • It then uses the setItem() method to update the mode item in the sessionStorage to the new one.

To view the data stored in the session storage in the web browser, you click the Application tab and select the Session Storage :