2023-11-27-posts.md 2.3 KB


title: newWindow storage description: Today I learned that you can use LocalStorage across multiple windows. slug: newwindow-storage <!--- authors:

Today I learned that you can use LocalStorage across multiple windows.

☝🏼 top video by Bjørn Staal 1

I could imagine a use case like some authentication and/or confirmation windows that open could have a subtle graphic reference to the origin window. Otherwise it's just fun and that's why I like it. Here's some example code from the repo:

constructor ()
{
  let that = this;

  // event listener for when localStorage is changed from another window
  addEventListener("storage", (event) => 
  {
    if (event.key == "windows")
    {
      let newWindows = JSON.parse(event.newValue);
      let winChange = that.#didWindowsChange(that.#windows, newWindows);

      that.#windows = newWindows;

      if (winChange)
      {
      if (that.#winChangeCallback) that.#winChangeCallback();
      }
    }
  });

  // event listener for when current window is about to be closed
  window.addEventListener('beforeunload', function (e) 
  {
    let index = that.getWindowIndexFromId(that.#id);

  //remove this window from the list and update local storage
    that.#windows.splice(index, 1);
    that.updateWindowsLocalStorage();
  });
}

I found some other examples floating around out there too3.


  1. Bjørn Gunnar Staal - X - https://twitter.com/_nonfigurativ_/status/1722543833408286927
  2. Bjørn Gunnar Staal - Github - https://github.com/bgstaal
  3. Momcilo Popov - Fun with Sockets - https://github.com/Momciloo/fun-with-sockets