Execute a script when a Web Storage area is updated in HTML?

The onstorage attribute in HTML is used to execute a script when the Web Storage area (localStorage or sessionStorage) is updated. This event is triggered when storage data changes in another window or tab of the same origin, making it useful for synchronizing data across multiple browser windows.

Syntax

Following is the syntax for the onstorage attribute −

<body onstorage="script">

The onstorage event is typically attached to the <body> element and fires when:

  • Another window or tab modifies localStorage

  • Another window or tab modifies sessionStorage

  • Storage items are added, modified, or removed from another browsing context

Note: The onstorage event does not fire in the same window that made the storage changes. It only fires in other windows/tabs of the same origin.

Using onstorage Attribute

Example − Basic onstorage Implementation

Following example demonstrates how to use the onstorage attribute to detect storage changes −

<!DOCTYPE html>
<html>
<head>
   <title>HTML onstorage Attribute</title>
</head>
<body onstorage="handleStorageChange(event)" style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Web Storage Detection Example</h2>
   <p>Open this page in multiple tabs and click the buttons to see storage synchronization.</p>
   
   <button onclick="addItem()">Add Item to Storage</button>
   <button onclick="updateItem()">Update Item</button>
   <button onclick="clearStorage()">Clear Storage</button>
   
   <div id="output" style="margin-top: 20px; padding: 10px; border: 1px solid #ccc; background: #f9f9f9;">
      <p>Storage events will appear here...</p>
   </div>

   <script>
      function handleStorageChange(event) {
         var output = document.getElementById('output');
         output.innerHTML = '<p><strong>Storage Event Detected!</strong></p>' +
                          '<p>Key: ' + event.key + '</p>' +
                          '<p>Old Value: ' + event.oldValue + '</p>' +
                          '<p>New Value: ' + event.newValue + '</p>' +
                          '<p>URL: ' + event.url + '</p>';
      }

      function addItem() {
         localStorage.setItem('userAction', 'Item Added at ' + new Date().toLocaleTimeString());
      }

      function updateItem() {
         localStorage.setItem('userAction', 'Item Updated at ' + new Date().toLocaleTimeString());
      }

      function clearStorage() {
         localStorage.clear();
      }
   </script>
</body>
</html>

Open this page in multiple browser tabs. When you click buttons in one tab, the onstorage event will fire in the other tabs, displaying the storage change details.

Example − Real-time Data Synchronization

Following example shows how to use onstorage for synchronizing user preferences across tabs −

<!DOCTYPE html>
<html>
<head>
   <title>Storage Sync Example</title>
</head>
<body onstorage="syncTheme(event)" style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Theme Synchronization Demo</h2>
   <p>Change the theme in one tab to see it sync in other tabs.</p>
   
   <button onclick="setTheme('light')">Light Theme</button>
   <button onclick="setTheme('dark')">Dark Theme</button>
   <button onclick="setTheme('blue')">Blue Theme</button>
   
   <div id="content" style="margin-top: 20px; padding: 15px; border-radius: 5px;">
      <h3>Sample Content</h3>
      <p>This content will change appearance based on the selected theme.</p>
   </div>

   <script>
      function setTheme(theme) {
         localStorage.setItem('selectedTheme', theme);
         applyTheme(theme);
      }

      function syncTheme(event) {
         if (event.key === 'selectedTheme') {
            applyTheme(event.newValue);
         }
      }

      function applyTheme(theme) {
         var content = document.getElementById('content');
         var body = document.body;
         
         if (theme === 'dark') {
            body.style.backgroundColor = '#333';
            body.style.color = '#fff';
            content.style.backgroundColor = '#555';
         } else if (theme === 'blue') {
            body.style.backgroundColor = '#e3f2fd';
            body.style.color = '#1565c0';
            content.style.backgroundColor = '#bbdefb';
         } else {
            body.style.backgroundColor = '#fff';
            body.style.color = '#333';
            content.style.backgroundColor = '#f5f5f5';
         }
      }

      // Apply saved theme on page load
      window.onload = function() {
         var savedTheme = localStorage.getItem('selectedTheme') || 'light';
         applyTheme(savedTheme);
      }
   </script>
</body>
</html>

When you change the theme in one tab, all other tabs automatically update to match the selected theme through the onstorage event.

Storage Event Properties

The onstorage event provides access to several useful properties −

  • event.key − The storage key that was changed

  • event.oldValue − The previous value of the key

  • event.newValue − The new value of the key

  • event.url − The URL of the page that made the change

  • event.storageArea − The storage object (localStorage or sessionStorage)

Example − Comprehensive Storage Event Handler

<!DOCTYPE html>
<html>
<head>
   <title>Complete Storage Event Example</title>
</head>
<body onstorage="logStorageEvent(event)" style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Storage Event Logger</h2>
   <button onclick="testStorage()">Test Storage Change</button>
   <pre id="log" style="background: #f0f0f0; padding: 10px; margin-top: 10px; white-space: pre-wrap;"></pre>

   <script>
      function logStorageEvent(event) {
         var log = document.getElementById('log');
         var timestamp = new Date().toLocaleTimeString();
         
         var eventData = timestamp + ' - Storage Event:
' + ' Key: ' + (event.key || 'null') + '
' + ' Old Value: ' + (event.oldValue || 'null') + '
' + ' New Value: ' + (event.newValue || 'null') + '
' + ' URL: ' + event.url + '
' + ' Storage Type: ' + (event.storageArea === localStorage ? 'localStorage' : 'sessionStorage') + '

'; log.textContent = eventData + log.textContent; } function testStorage() { var timestamp = Date.now(); localStorage.setItem('testKey', 'Test value at ' + timestamp); } </script> </body> </html>

This example logs detailed information about storage events, including all available event properties.

How onstorage Event Works Tab 1 Makes storage changes (no event fires) Tab 2 Receives onstorage event Storage event localStorage / sessionStorage Shared storage area

Browser Compatibility

The onstorage event is supported in all modern browsers including Chrome, Firefox, Safari, Edge, and Internet Explorer 8+. However, some older browsers may have limited support for certain event properties.

Common Use Cases

The onstorage attribute is commonly used for −

  • User preference synchronization across multiple tabs

  • Real-time data updates in web applications

  • Shopping cart synchronization in e-commerce sites

  • Authentication state management across browser tabs

  • Theme or layout changes that persist across sessions

Conclusion

The onstorage attribute provides an effective way to detect and respond to Web Storage changes across multiple browser tabs or windows. It enables real-time synchronization of data and user preferences, creating a more cohesive user experience across different browsing contexts of the same origin.

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

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements