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.
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.