Recipe 2.5

Listening for Storage Changes

Open this page in a second tab. With two tabs open, change the selected color in one of the tabs. When you return to the other tab, the color will have been updated due to a storage event. A message will be logged in the console when a storage event is received.

Demo

Code

JavaScript
// A reference to the color picker input element.
const colorPicker = document.querySelector('#colorPicker');

// Load the saved color, if any, and set it on the color picker.
const storedValue = localStorage.getItem('savedColor');
if (storedValue) {
  console.log('Found saved color:', storedValue);
  colorPicker.value = storedValue;
}

// Update the saved color whenever the value changes.
colorPicker.addEventListener('change', event => {
  localStorage.setItem('savedColor', colorPicker.value);
  console.log('Saving new color:', colorPicker.value);
});

// Listen for the `storage` event. If another tab changes the
// `savedColor` item, update this page's color picker with the new value.
window.addEventListener('storage', event => {
  if (event.key === 'savedColor') {
    console.log('New color was chosen in another tab:', event.newValue);
    colorPicker.value = event.newValue;
  }
});
HTML
<div>
  <label for="colorPicker" class="form-label">Choose a color</label>
  <input id="colorPicker" class="form-control" type="color">
</div>
Web API Cookbook
Joe Attardi