Localstorage 具有您可以订阅以同步其他页面的事件。
注意:如果您更新窗口 A 中的键值,该事件将not在窗口 A 中触发。在窗口 B 和 C 中也会触发。
这是一个演示:http://html5demos.com/storage-events
在多个选项卡中打开此页面。更改输入的值并查看它反映在 div 中。
这是 JavaScript 代码:
var dataInput = document.getElementById('data'),
output = document.getElementById('fromEvent');
// handle updates to the storage-event-test key in other windows
addEvent(window, 'storage', function (event) {
if (event.key == 'storage-event-test') {
output.innerHTML = event.newValue;
}
});
// Update the storage-event-test key when the value on the input is changed
addEvent(dataInput, 'keyup', function () {
localStorage.setItem('storage-event-test', this.value);
});
Markup:
<div>
<p>Your test data: <input type="text" name="data" value="" placeholder="change me" id="data" /> <small>(this is only echoed on <em>other</em> windows)</small></p>
<p id="fromEvent">Waiting for data via <code>storage</code> event...</p>
</div>
HTML 5 规范讨论了事件中传递的所有信息:
[Constructor(DOMString type, optional StorageEventInit eventInitDict)]
interface StorageEvent : Event {
readonly attribute DOMString key;
readonly attribute DOMString? oldValue;
readonly attribute DOMString? newValue;
readonly attribute DOMString url;
readonly attribute Storage? storageArea;
};
dictionary StorageEventInit : EventInit {
DOMString key;
DOMString? oldValue;
DOMString? newValue;
DOMString url;
Storage? storageArea;
};
From: http://www.w3.org/TR/webstorage/#the-storage-event
使用此事件,您可以使其他页面在本地存储中的特定键更新时做出反应。