JavaScript Storage Event newValue Property: Understanding the New Storage Value

The JavaScript Storage Event is a crucial tool for handling changes in web storage (both localStorage and sessionStorage) across different browser contexts. When a storage item is added, modified, or removed, a storage event is triggered on any other document that is listening to it within the same origin. The newValue property of this event provides the new value of the changed storage item, allowing you to respond dynamically to these changes.

What is the Storage Event newValue Property?

The newValue property of a StorageEvent object contains the value of the storage item after the change occurred. This is particularly useful when you need to update the user interface or perform other actions based on the new state of the storage. It’s essential for maintaining consistency across multiple browser tabs or windows that share the same storage.

  • Purpose: To retrieve the new value of a storage item when a storage event is triggered.
  • Type: String or null (if the item is removed).
  • Read-Only: This property cannot be modified directly.

Syntax

The syntax for accessing the newValue property is straightforward:

event.newValue

Where event is the StorageEvent object passed to the event handler.

Understanding the storage Event

Before diving deeper, let’s quickly recap how the storage event works:

  1. Storage Modification: When you use localStorage.setItem(), localStorage.removeItem(), or sessionStorage equivalents on a document, any other document with the same origin will trigger storage event.
  2. Event Trigger: When a storage item is changed, the storage event is dispatched to all other window contexts that share the same origin and are listening to it.
  3. StorageEvent Object: The storage event will have an event object containing details about the change, like newValue, key, oldValue, storageArea, and url.

Using the newValue Property

Now, let’s explore practical examples of how to use the newValue property.

Example 1: Basic Usage

In this example, we’ll set a storage item in one window and observe the change in another window.

HTML (index.html – first window):

<!DOCTYPE html>
<html>
<head>
    <title>Storage Event Example - Window 1</title>
</head>
<body>
  <h1>Window 1</h1>
  <button id="updateStorageBtn">Update Storage</button>

  <script>
      const updateStorageBtn1 = document.getElementById("updateStorageBtn");

      updateStorageBtn1.addEventListener("click", function() {
          localStorage.setItem("myKey", Date.now().toString());
        console.log("Storage updated in window 1");
      });

</script>
</body>
</html>

HTML (another.html – second window):

<!DOCTYPE html>
<html>
<head>
    <title>Storage Event Example - Window 2</title>
</head>
<body>
    <h1>Window 2</h1>
    <div id="outputDiv2"></div>
    <script>
        const outputDiv2 = document.getElementById("outputDiv2");
        window.addEventListener('storage', function(event) {
            if (event.key === 'myKey') {
                outputDiv2.innerHTML = `New Value: ${event.newValue}`;
              console.log("Storage updated in window 2");
            }
        });

</script>
</body>
</html>

Steps to test:

  1. Open index.html and another.html in two browser windows or tabs.
  2. Click the “Update Storage” button in index.html.
  3. Observe the output of the new value in another.html.

Explanation:

  • In index.html, clicking the button sets the item "myKey" in localStorage to the current timestamp.
  • In another.html, the storage event listener checks if the key of the event is "myKey". If so, it outputs the newValue.

Example 2: Handling Removal of Storage Item

Here, we handle a case where an item is removed and newValue will be null.

HTML (remove.html – first window):

<!DOCTYPE html>
<html>
<head>
    <title>Storage Event Example - Removal</title>
</head>
<body>
    <h1>Window 1</h1>
    <button id="removeStorageBtn">Remove Storage Item</button>
    <script>
        const removeStorageBtn1 = document.getElementById("removeStorageBtn");
        removeStorageBtn1.addEventListener("click", function() {
           localStorage.removeItem("myKey");
           console.log("Storage item removed in window 1");
        });

</script>
</body>
</html>

HTML (observer.html – second window):

<!DOCTYPE html>
<html>
<head>
    <title>Storage Event Example - Observer</title>
</head>
<body>
    <h1>Window 2</h1>
    <div id="removalOutput"></div>
    <script>
        const removalOutput2 = document.getElementById("removalOutput");
        window.addEventListener('storage', function(event) {
            if (event.key === 'myKey') {
                if(event.newValue === null) {
                   removalOutput2.innerHTML = 'Item was removed!';
                }
                else
                {
                  removalOutput2.innerHTML = `New value: ${event.newValue}`;
                }

              console.log("Storage changed in window 2");
            }
        });

</script>
</body>
</html>

Steps to test:

  1. Open remove.html and observer.html in two separate browser windows.
  2. First set a value myKey using first example if you don’t have a value.
  3. Click the “Remove Storage Item” button in remove.html.
  4. Observe the message in observer.html.

Explanation:

  • In remove.html, the button click removes "myKey" using localStorage.removeItem().
  • In observer.html, the storage event listener checks if the key is "myKey". The newValue will be null, then the output message gets displayed.

Example 3: Using newValue with sessionStorage

The same principles apply to sessionStorage, allowing you to handle changes in the session.

HTML (session-setter.html – first window):

<!DOCTYPE html>
<html>
<head>
    <title>Session Storage Setter</title>
</head>
<body>
  <h1>Window 1</h1>
    <button id="updateSessionBtn">Update Session</button>
  <script>
    const updateSessionBtn3 = document.getElementById("updateSessionBtn");
    updateSessionBtn3.addEventListener('click', function() {
       sessionStorage.setItem('sessionKey', 'Updated Value');
     console.log("Session Storage updated in window 1");
    });

</script>
</body>
</html>

HTML (session-observer.html – second window):

<!DOCTYPE html>
<html>
<head>
    <title>Session Storage Observer</title>
</head>
<body>
  <h1>Window 2</h1>
    <div id="sessionOutput"></div>
    <script>
        const sessionOutput3 = document.getElementById('sessionOutput');
        window.addEventListener('storage', function(event) {
          if(event.key === 'sessionKey') {
              sessionOutput3.innerHTML = `Session New Value: ${event.newValue}`;
            console.log("Session Storage updated in window 2");
          }
        });

</script>
</body>
</html>

Steps to test:

  1. Open session-setter.html and session-observer.html in two different windows/tabs.
  2. Click the “Update Session” button in session-setter.html.
  3. See the changes reflected in session-observer.html.

Explanation:

  • In session-setter.html, the button click sets "sessionKey" in sessionStorage.
  • In session-observer.html, the listener catches the event and displays the new value from event.newValue.

Note: The storage event is only triggered in other contexts, not in the context where the change was made. 💡

Key Points about newValue

  • The newValue property always returns a string, or null if the storage item was removed.
  • It’s a read-only property; you cannot modify it.
  • It reflects the state of the storage after the change occurred.
  • It plays an important role in keeping multiple browser contexts in sync, especially in web applications that utilize local or session storage for state management.

Real-World Use Cases

  1. Cross-Tab Communication: Update user preferences or shopping cart data across different browser tabs.
  2. Real-Time Updates: Display changes made by one user to all other users in the same session in real-time.
  3. Offline Data Handling: When online after being offline, update the data if changed by another tab.

Browser Support

The storage event and its properties including newValue are widely supported across modern browsers, ensuring consistent behavior.

Note: Always test your code across different browsers to ensure compatibility and expected behavior. 🧐

Conclusion

The newValue property of the JavaScript Storage Event is a fundamental aspect of web storage handling. By effectively leveraging the storage event and the newValue property, you can build more robust and responsive web applications that communicate and update storage states in real time across multiple browser contexts. This powerful combination of event-driven architecture and local data persistence opens a world of possibilities for creating sophisticated and user-friendly web experiences.