Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker 诊断工具


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

JavaScript 大约 1033 字

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>

应用

不同标签页同步用户登录状态

阅读 2157 · 发布于 2021-06-11

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

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

扫描二维码关注我
昵称:
随便看看 换一批