title: Communication between tabs or windows
body: <p>I was searching for a way how to communicate between multiple tabs or windows in a browser (on the same domain, not <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" rel="noreferrer">CORS</a>) without leaving traces. There were several solutions:</p>
  <ol>
  <li><a href="https://stackoverflow.com/questions/4167965/how-do-you-communicate-between-2-browser-tabs-windows">using the <em>window</em> object</a></li>
  <li><a href="https://stackoverflow.com/questions/2236828/javascript-communication-between-tabs-windows-with-same-origin/12514384">postMessage</a></li>
  <li><a href="https://stackoverflow.com/questions/4079280/javascript-communication-between-browser-tabs-windows/4079423#4079423">cookies</a></li>
  <li><a href="https://stackoverflow.com/questions/1100336/sending-a-message-to-all-open-windows-tabs-using-javascript">localStorage</a></li>
  </ol>
  <p>The first is probably the worst solution - you need to open a window from your current window and then you can communicate only as long as you keep the windows open. If you reload the page in any of the windows, you most likely lost the communication.</p>
  <p>The second approach, using postMessage, probably enables cross-origin communication, but it suffers the same problem as the first approach. You need to maintain a window object.</p>
  <p>The third way, using cookies, store some data in the browser, which can effectively look like sending a message to all windows on the same domain, but the problem is that you can never know if all tabs read the &quot;message&quot; already or not before cleaning up. You have to implement some sort of timeout to read the cookie periodically. Furthermore you are limited by maximum cookie length, which is 4 KB.</p>
  <p>The fourth solution, using localStorage, seemed to overcome the limitations of cookies, and it can be even listen-to using events. How to use it is described in the accepted answer.</p>
  <p>In 2018, the accepted answer still works, but there is a newer solution for modern browsers, to use BroadcastChannel. See the other answer for a simple example describing how to easily transmit message between tabs by using BroadcastChannel.</p>