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