--- title: newWindow storage description: Today I learned that you can use LocalStorage across multiple windows. slug: newwindow-storage <!--- authors: - name: David Windham title: Something Else url: https://davidawindham.com image_url: https://davidawindham.com/wp-content/themes/daw/img/opengraph_image.jpg --> tags: [js, webgl, threejs] image: https://davidawindham.com/wp-content/themes/daw/img/opengraph_image.jpg hide_table_of_contents: true --- Today I learned that you can use LocalStorage across multiple windows. <!--truncate--> <video src="https://davidawindham.com/media/localstorage-3js.mp4" width="100%" controls="controls"> </video> <video src="https://davidawindham.com/media/newWindow-3js.mp4" width="100%" controls="controls"> </video> <div style={{display: 'flex', justifyContent:'center', alignItems:'center', fontSize:'small', marginBottom:'20px'}}>☝🏼 top video by Bjørn Staal <sub>1</sub></div> 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](https://github.com/bgstaal/multipleWindow3dScene): ```js 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 too<sub>3</sub>. --- 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