javascriptbrowserdom-eventssession-storage

Why does the `storage` event exist for `sessionStorage` if it doesn't propagate across tabs?


MDN Web Docs says that

"The storage event of the Window interface fires when a storage area (localStorage or sessionStorage) has been modified in the context of another document."

However

So if we change some data in Tab1 sessionStorage, event should fire in Tab2, Tab3, etc. but at the same time, the data from sessionStorage should only be accessible within Tab1, which is confisuing for me.

I tested this behavior with the following code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Storage Event Test</title>
  <script>
    function setSessionStorage() {
      sessionStorage.setItem('sessionKey', 'sessionValue');
      console.log('sessionStorage set:', sessionStorage.getItem('sessionKey'));
    }

    function setLocalStorage() {
      localStorage.setItem('localKey', 'localValue');
      console.log('localStorage set:', localStorage.getItem('localKey'));
    }

    window.addEventListener('storage', (event) => {
      console.log('Storage event detected!');
      console.log('Key:', event.key);
      console.log('Old Value:', event.oldValue);
      console.log('New Value:', event.newValue);
      console.log('Storage Area:', event.storageArea);
    });
  </script>
</head>
<body>
  <h1>Test Storage Event</h1>
  <button onclick="setSessionStorage()">Set sessionStorage</button>
  <button onclick="setLocalStorage()">Set localStorage</button>
</body>
</html>

I opened this page in two tabs, and when I changed sessionStorage on Tab1, Tab2 didn't detect storage event (unlike withlocalStorage).

So, my question is: Why does storage event for sessionStorage exists, if it's not accessible from anywhere?


Solution

  • It's possible to have multiple documents in a single tab using an iframe, in which case the event is accessible.

    index.html

    <!DOCTYPE html>
    <html>
        <head>
            <title>index</title>
            <script>
                window.addEventListener('storage', e => {
                    console.log(e);
                });
            </script>
        </head>
        <body>
            <iframe src="frame.html"></iframe>
        </body>
    </html>
    

    frame.html

    <!DOCTYPE html>
    <html>
        <head>
            <title>frame</title>
        </head>
        <body>
            <script>
                sessionStorage.setItem('test', Date.now());
            </script>
        </body>
    </html>