HTML DOM Storage Event

The HTML DOM storage event is triggered when changes occur in the browser's storage areas (localStorage or sessionStorage). This event fires when another window, tab, or frame modifies the storage, making it useful for synchronizing data across multiple windows of the same origin.

The storage event is particularly valuable for creating real-time communication between different browser windows or tabs without requiring server-side communication. It only triggers when the storage change originates from a different browsing context, not from the current window itself.

Syntax

Following is the syntax for adding a storage event listener −

window.addEventListener("storage", function(event) {
    // Handle storage changes
});

The event object contains the following properties −

event.key         // The key that was changed
event.oldValue    // The old value (null if new key)
event.newValue    // The new value (null if key removed)
event.url         // The URL of the document that changed storage
event.storageArea // Reference to localStorage or sessionStorage

Storage Event Properties

The storage event provides detailed information about the storage change through its event object properties −

Property Description
key The name of the key that was added, modified, or removed
oldValue The previous value of the key (null for new keys)
newValue The new value of the key (null for removed keys)
url The URL of the document where the storage was changed
storageArea Reference to either localStorage or sessionStorage object

Basic Storage Event Example

Following example demonstrates how to listen for storage events and display the changed data −

<!DOCTYPE html>
<html>
<head>
    <title>Storage Event Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
    <h2>Storage Event Listener</h2>
    <p>Open this page in another tab and modify localStorage to see the event trigger.</p>
    <button onclick="createData()">Create Data in New Window</button>
    <div id="output" style="margin-top: 20px; padding: 10px; background: #f5f5f5; border: 1px solid #ccc;">
        <p>Storage events will appear here...</p>
    </div>
    
    <script>
        window.addEventListener("storage", function(event) {
            const output = document.getElementById("output");
            output.innerHTML += "<p><strong>Storage Event Detected:</strong><br>" +
                               "Key: " + event.key + "<br>" +
                               "Old Value: " + event.oldValue + "<br>" +
                               "New Value: " + event.newValue + "<br>" +
                               "URL: " + event.url + "</p>";
        });
        
        function createData() {
            const newWindow = window.open("", "testWindow", "width=400,height=300");
            newWindow.document.write(`
                <html><body style="font-family: Arial; padding: 20px;">
                <h3>Test Window</h3>
                <button onclick="localStorage.setItem('testKey', 'Hello from new window!')">Set Storage</button>
                <button onclick="localStorage.removeItem('testKey')">Remove Storage</button>
                </body></html>
            `);
            setTimeout(() => newWindow.close(), 10000);
        }
    </script>
</body>
</html>

The storage event fires when the new window modifies localStorage, and the original window receives the event with all relevant details.

Cross-Tab Communication Example

Following example shows how to use storage events for real-time communication between browser tabs −

<!DOCTYPE html>
<html>
<head>
    <title>Cross-Tab Communication</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
    <h2>Cross-Tab Message System</h2>
    <p>Open this page in multiple tabs to test real-time communication.</p>
    
    <div style="margin: 20px 0;">
        <input type="text" id="messageInput" placeholder="Enter message..." style="padding: 8px; width: 300px;">
        <button onclick="sendMessage()" style="padding: 8px 15px;">Send to Other Tabs</button>
    </div>
    
    <div id="messages" style="border: 1px solid #ccc; padding: 10px; height: 200px; overflow-y: auto; background: #f9f9f9;">
        <p>Messages from other tabs will appear here...</p>
    </div>
    
    <script>
        window.addEventListener("storage", function(event) {
            if (event.key === "crossTabMessage") {
                const messagesDiv = document.getElementById("messages");
                const messageData = JSON.parse(event.newValue);
                messagesDiv.innerHTML += "<p><strong>" + messageData.timestamp + ":</strong> " + messageData.message + "</p>";
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            }
        });
        
        function sendMessage() {
            const input = document.getElementById("messageInput");
            if (input.value.trim()) {
                const messageData = {
                    message: input.value,
                    timestamp: new Date().toLocaleTimeString()
                };
                localStorage.setItem("crossTabMessage", JSON.stringify(messageData));
                input.value = "";
            }
        }
    </script>
</body>
</html>

Open this page in multiple browser tabs. When you send a message from one tab, it appears in all other tabs instantly through the storage event mechanism.

Monitoring Storage Changes

Following example creates a comprehensive storage monitor that tracks all localStorage changes −

<!DOCTYPE html>
<html>
<head>
    <title>Storage Monitor</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
    <h2>localStorage Monitor</h2>
    <p>This page monitors all localStorage changes from other windows/tabs.</p>
    
    <div style="margin: 20px 0;">
        <button onclick="openTestWindow()">Open Test Window</button>
        <button onclick="clearLog()">Clear Log</button>
    </div>
    
    <div id="log" style="border: 1px solid #333; padding: 10px; height: 300px; overflow-y: auto; background: #000; color: #0f0; font-family: monospace;">
        <div>Storage monitor active...</div>
    </div>
    
    <script>
        window.addEventListener("storage", function(event) {
            const log = document.getElementById("log");
            const timestamp = new Date().toLocaleTimeString();
            
            let action = "MODIFIED";
            if (event.oldValue === null) action = "CREATED";
            if (event.newValue === null) action = "DELETED";
            
            log.innerHTML += "<div>[" + timestamp + "] " + action + " - Key: '" + event.key + "'</div>";
            if (event.oldValue !== null) {
                log.innerHTML += "<div>  Old: " + event.oldValue + "</div>";
            }
            if (event.newValue !== null) {
                log.innerHTML += "<div>  New: " + event.newValue + "</div>";
            }
            log.innerHTML += "<div>  From: " + event.url + "</div><br>";
            log.scrollTop = log.scrollHeight;
        });
        
        function openTestWindow() {
            const testWindow = window.open("", "storageTest", "width=400,height=400");
            testWindow.document.write(`
                <html><body style="font-family: Arial; padding: 20px;">
                <h3>Storage Test Window</h3>
                <input id="key" placeholder="Key" style="display: block; margin: 5px 0; padding: 5px; width: 200px;">
                <input id="value" placeholder="Value" style="display: block; margin: 5px 0; padding: 5px; width: 200px;">
                <button onclick="localStorage.setItem(document.getElementById('key').value, document.getElementById('value').value)">Set Item</button>
                <button onclick="localStorage.removeItem(document.getElementById('key').value)">Remove Item</button>
                <button onclick="localStorage.clear()">Clear All</button>
                </body></html>
            `);
        }
        
        function clearLog() {
            document.getElementById("log").innerHTML = "<div>Storage monitor active...</div>";
        }
    </script>
</body>
</html>

This example creates a real-time monitor that logs all localStorage changes with timestamps, showing whether items were created, modified, or deleted.

Key Points About Storage Events

  • Origin Restriction − Storage events only fire for changes from other windows/tabs of the same origin (same protocol, domain, and port).

  • No Self-Triggering − A window does not receive storage events for its own localStorage/sessionStorage changes.

  • Both Storage Types − The event works for both localStorage and sessionStorage modifications.

  • Event Timing − The storage event fires after the storage change has been completed.

  • Browser Support − All modern browsers support storage events, but older versions of Internet Explorer may have limitations.

Conclusion

The HTML DOM storage event provides a powerful mechanism for real-time communication between browser windows and tabs of the same origin. It enables applications to synchronize data and create responsive multi-window experiences without server-side infrastructure. The event fires automatically when localStorage or sessionStorage is modified by other browsing contexts, making it ideal for cross-tab messaging and data synchronization.

Updated on: 2026-03-16T21:38:54+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements