JavaScript onstorage 监听本地存储变更事件
JavaScript About 1,033 wordsonstorage
入参e
有几个字段:
e.key
:设置的key
e.oldValue
:原先的值e.newValue
:新设置的值
window.onstorage = function (e) {
}
注意
Chrome
浏览器不会在当前标签页触发onstorage
事件,IE
浏览器则同时在所有标签页触发。需要使用document.hasFocus()
判断是否是当前标签页。
完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function saveTo() {
localStorage.setItem("change-event", new Date().toJSON())
}
window.onstorage = function (e) {
console.log(e)
console.log(`The ${e.key} key has been changed from ${e.oldValue} to ${e.newValue}.`);
console.log(document.hasFocus())
// IE will receive the event both the current tab and other tab
if (!document.hasFocus() && e.key === "change-event") {
console.log("do some business")
}
};
</script>
</head>
<body>
<button onclick="saveTo()">click</button>
</body>
</html>
应用
Views: 3,436 · Posted: 2021-06-10
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...