localstorage
和sessionStorage
为现代浏览器提供用户会话级别的数据存取。Document
源(origin)的对象 Storage
,也就是在遵照同源策略
状况下存取数据。localstorage
和sessionStorage
API的基本用法,而是列举storage
在一些经常使用库中的用法,促使你对浏览器storage
存取数据更多可能性的思考。storageEvent事件
的用法use-persisted-state
中storage的用法storageEvent事件
当前页面使用的storage被其余页面修改时会触发StorageEvent事件(来源MDN)。 javascript
说明:符合同源策略,在同一浏览器下的不一样窗口, 当焦点页之外的其余页面致使数据变化时,若是焦点页监听storage事件,那么该事件会触发, 换一种说法就是除了改变数据的当前页不会响应外,其余窗口都会响应该事件。html
window.addEventListener("storage",function(event) { console.log(event); }); /** event的属性: key:该属性表明被修改的键值。当被clear()方法清除以后该属性值为null。(只读) oldValue:该属性表明修改前的原值。在设置新键值对时因为没有原始值,该属性值为 null。(只读) newValue:修改后的新值。若是该键被clear()方法清理后或者该键值对被移除,,则这个属性为null。 url:key 发生改变的对象所在文档的URL地址。(只读) */
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] );
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