mlo*_*sev 5 javascript session-storage local-storage
如果我设置了localStorage项目,StorageEvent则为除当前之外的所有同域窗口触发。
如果我以StorageEvent编程方式引发,则StorageEvent仅针对目标窗口触发。
代码示例:
var evt = document.createEvent('StorageEvent');
evt.initStorageEvent('storage',false,false,'key','oldValue','newValue',
'http://example.com',window.localStorage);
window.dispatchEvent(evt);
Run Code Online (Sandbox Code Playgroud)
我可以修改代码示例以模拟来自 window.setItem
小智 -2
您可以创建一个指向相同原点的 iframe(about:blank符合这样的条件)并localStorage在其中设置一个值contentWindow,以使事件在指向相同原点的任何其他窗口上触发并侦听存储事件:
window.addEventListener(\'storage\', function(e) {console.log(\'storage event\', e)});\niframe = document.createElement(\'iframe\');\niframe.src = \'about:blank\';\ndocument.body.appendChild(iframe);\niframe.contentWindow.localStorage.setItem(\'test\', \'value1\');\nRun Code Online (Sandbox Code Playgroud)\n\n输出:
\n\nstorage event \nStorageEvent {\n isTrusted: true,\n key: "test",\n oldValue: null,\n newValue: "value1",\n url: "about:blank",\n \xe2\x80\xa6\n}\nRun Code Online (Sandbox Code Playgroud)\n