Using onstorage event with localStorage

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

by Konstantin Rouda

HTML

<button id="btn">Add To LocalStorage</button>

JavaScript

;(function () {
  "use strict";
  
  const btn = document.getElementById("btn");
  
  btn.addEventListener("click", onBtnClick);
  
  function onBtnClick (e) {
    const d = new Date();
    const hours = d.getHours();
    const minutes = d.getMinutes();
    const seconds = d.getSeconds();
    window.localStorage.setItem("param", `${hours}:${minutes}:${seconds}`);
  };
  
  window.addEventListener("storage", onStorageChange);
  
  
  function onStorageChange (e) {
    debugger;
    const {key, newValue, oldValue} = e;
    console.log(`key: ${key}\nnewValue: ${newValue}\noldValue: ${oldValue}`);
  };
  
})();

/*
https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event


we can also use 
BroadcastChannel API (lacks support in Safari as of 07.2020)

https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API

https://dev.to/dcodeyt/send-data-between-tabs-with-javascript-2oa
*/