浏览器storage你真的会用吗

IMG_20191004_191646R_2.jpg

前言

  • html5标准localstoragesessionStorage 为现代浏览器提供用户会话级别的数据存取。
  • 它们允许你访问一个Document 源(origin)的对象 Storage,也就是在遵守同源策略情况下存取数据。
  • 本文重点不是localstoragesessionStorageAPI的基本用法,而是列举storage在一些常用库中的用法,促使你对浏览器storage存取数据更多可能性的思考。

阅读本文你将收获什么?

  • storageEvent事件的用法
  • 了解use-persisted-state中storage的用法

正文

1. storageEvent事件

当前页面使用的storage被其他页面修改时会触发StorageEvent事件(来源MDN)。

说明:符合同源策略,在同一浏览器下的不同窗口, 当焦点页以外的其他页面导致数据变化时,如果焦点页监听storage事件,那么该事件会触发, 换一种说法就是除了改变数据的当前页不会响应外,其他窗口都会响应该事件。

2. 用法
window.addEventListener("storage",function(event) {
    console.log(event);
});
/**
event的属性:
key:该属性代表被修改的键值。当被clear()方法清除之后该属性值为null。(只读)
oldValue:该属性代表修改前的原值。在设置新键值对时由于没有原始值,该属性值为 null。(只读)  
newValue:修改后的新值。如果该键被clear()方法清理后或者该键值对被移除,,则这个属性为null。  
url:key 发生改变的对象所在文档的URL地址。(只读)
*/
3. React hook 状态管理use-persisted-state中的用法
useEventListener('storage', ({ key: k, newValue }) => {
  if (k === key) {
    const newState = JSON.parse(newValue);
    if (state !== newState) {
      setState(newState);
    }
  }
});

// 监听state变化
// Only persist to storage if state changes.
useEffect(
  () => {
    // persist to localStorage
    set(key, state);

    // inform all of the other instances in this tab
    globalState.current.emit(state);
  },
  [state]
);
4. iframe中使用

同样符合同源策略的iframe也可以触发storage事件,利用iframe可以实现当前页不触发storageEvent事件的问题,方案如下:

btn.onclick = function () {
  if (iframe) {
    iframe.contentWindow.localStorage.setItem("key", val.value);
  }
};

window.addEventListener("storage", function (e) {
  console.log(e);
});

function prepareFrame() {
  iframe = document.createElement("iframe");
  document.body.appendChild(iframe);
  iframe.style.display = "none";
}
prepareFrame();
利用 storageEvent事件还可以做哪些事情那?欢迎留言讨论
注意:

IE浏览器除外,它会在所有页面触发storage事件。

你可能感兴趣的:(localstorage,javascript,html5)