如何监听localStorage变化

本地存储localStorage同页面监听,重写localStorage的方法,抛出自定义事件:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>监听localStorage变化(同页面)</title>
</head>
<body>
<button class="add">add</button>
<button class="add1">add1</button>
<button class="del">del</button>
<script src="http://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
        crossorigin="anonymous"></script>
<script>
    var orignalSetItem = localStorage.setItem;
    localStorage.setItem = function(key,newValue){
        var setItemEvent = new Event("setItemEvent");
        setItemEvent.key = key;
        setItemEvent.newValue = newValue;
        window.dispatchEvent(setItemEvent);
        orignalSetItem.apply(this,arguments);
    };
    window.addEventListener("setItemEvent", function (e) {
        if(e.key=='demo'){
            var _this=localStorage.getItem("demo")
            if(_this!=e.newValue){
                alert('key值为demo的值发生改变,之前是'+_this+'当前为'+e.newValue)
            }else{
                alert('key值为demo值'+e.newValue);
            }
        }
    });
    $('.add').click(function () {
        localStorage.setItem("demo","123");
    })
    $('.add1').click(function () {
        localStorage.setItem("demo","111");
    })
 
 
 
    var orignalremoveItem = localStorage.removeItem;
    localStorage.removeItem = function(key,newValue){
        var removeItemEvent = new Event("removeItemEvent");
        removeItemEvent.key = key;
        removeItemEvent.newValue = newValue;
        window.dispatchEvent(removeItemEvent);
        orignalremoveItem.apply(this,arguments);
    };
    window.addEventListener("removeItemEvent", function (e) {
        if(localStorage.getItem("demo")){
            if(e.key=='demo'){
                alert("key值为demo,删除成功");
            }
        }else{
            alert("本地数据无key值为demo")
        }
    });
    $(".del").click(function () {
        localStorage.removeItem('demo')
    })
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/art-poet/p/12628225.html