JavaScript onstorage 监听本地存储变更事件

JavaScript About 1,033 words

onstorage

入参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

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh