浏览器storage你真的会用吗

IMG_20191004_191646R_2.jpg

前言

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

阅读本文你将收获什么?

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

正文

1. storageEvent事件

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

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

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事件的问题,方案以下:html5

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事件。java

相关文章
相关标签/搜索