Whenever a value in set in localStorage, a storage
event will be dispatched on all other windows
from the same origin. This can be used to synchronize state between different pages without reloading or communicating with a server. For example, we can reflect the value of an input element as paragraph text in another window:
var input = document.createElement('input');
document.body.appendChild(input);
input.value = localStorage.getItem('user-value');
input.oninput = function(event) {
localStorage.setItem('user-value', input.value);
};
Second Window
var output = document.createElement('p');
document.body.appendChild(output);
output.textContent = localStorage.getItem('user-value');
window.addEventListener('storage', function(event) {
if (event.key === 'user-value') {
output.textContent = event.newValue;
}
});
Event is not fired or catchable under Chrome, Edge and Safari if domain was modified through script.
First window// page url: http://sub.a.com/1.html
document.domain = 'a.com';
var input = document.createElement('input');
document.body.appendChild(input);
input.value = localStorage.getItem('user-value');
input.oninput = function(event) {
localStorage.setItem('user-value', input.value);
};
Second Window
// page url: http://sub.a.com/2.html
document.domain = 'a.com';
var output = document.createElement('p');
document.body.appendChild(output);
// Listener will never called under Chrome(53), Edge and Safari(10.0).
window.addEventListener('storage', function(event) {
if (event.key === 'user-value') {
output.textContent = event.newValue;
}
});