We all know that window.onstorage must meet the following two conditions:

  1. Save (update) a storage with localstorage. setItem or sessionStorage.setItem
  2. When the storage is saved (updated), its new value must be different from the previous value

Initializing storage (null); initializing storage (null); Or an update to an existing storage

For example:

// Initialize the storage
window.localStorage.setItem('a'.123);

// Register the onStorage event
window.onstorage = (e) = > {
  console.log(e);
};

/ / update of storage
window.localStorage.setItem('a'.123);
Copy the code

The last line of code above does not trigger the onstorage event because the value of A has not changed, 123 before and after, so the browser decides that the update is invalid

Because the onstorage event is triggered by the browser, so if we open the multiple page under the same domain name, and in which any one page window. The localStorage. SetItem method (and ensure that meet the article mentioned the beginning the second condition). If other pages listen for onStorage events, the onStorage event callback in those pages will be executed

For example:

// http://www.example.com/a.html
<script>
// Register the onStorage event
window.onstorage = (e) = > {
  console.log(e);
};
</script>
Copy the code
// http://www.example.com/b.html
<script>
// Register the onStorage event
window.onstorage = (e) = > {
  console.log(e);
};
</script>
Copy the code
// http://www.example.com/c.html
<script>
// Trigger the onstorage event
window.localStorage.setItem('a'.new Date().getTime());
</script>
Copy the code

As long as page C is opened after page A and page B (even if the three pages are not in the same browser window), the onstorage event in page A and page B will be triggered

Now that we know how to use storage Events to communicate between pages, what is the use of this communication for us? We only need to know which storage triggered the onStorage event, so how do we know? The onStorage event callback, like the other event callback functions, receives an event object argument with three useful properties:

  1. Key Key name of the storage that is initialized or updated
  2. OldValue Specifies the value before the initialized or updated storage
  3. NewValue Specifies the value after the initialized or updated storage

By combining these three key attributes, we can achieve data synchronization between pages

Finally, the difference between localStorage and sessionStorage is mentioned

Data stored in localStorage has no expiration date, while data stored in sessionStorage is cleared when the page session ends

The original address: www.guoyunfeng.com/2018/07/22/…