Storage事件监听

作者: akubaba | 来源:发表于2017-11-30 19:30 被阅读650次

    一、功能

    1、前台页面:访问地址index.html?rid=参数id,点击点播
    2、后台管理员管理页面实时收到点播信息
    简单页面:


    前台页面index.html
    后台页面new.html

    二、实现

    跨页面通信可以用localstorage实现。

    1、关于localstorage

    (1)写入,localStorage只支持string类型的存储

    function play(){
            if(!window.localStorage){
                alert("浏览器不支持localstorage");
                return false;
            }else{
                //主逻辑业务
                localStorage.clear();
                //写入的几种形式
                localStorage.rid = '1';
                //localStorage['rid']=1;
                //localStorage.setItem('rid',1);
            }
        }
    

    可以用谷歌自带的插件查看:


    查看localStorage写入情况

    (2)读取

    if(!window.localStorage){
            alert("浏览器不支持localstorage");
        }else{
            alert(localStorage.rid);
            //alert(localStorage['rid']);
            //alert(localStorage.getItem('rid'));
        }
    

    (3)storage事件监听(要在服务器下运行)

    window.addEventListener("storage", function (e) {
            alert(e.newValue);
    });
    

    2、放效果图

    效果图

    3、最终实现代码

    <!-- index.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        这里是一部电影的简介
        <button id="play">点播</button>
    </body>
    <script type="text/javascript">
        //读取当前url参数
        function getQueryString(name){
            var reg=new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r=window.location.search.substr(1).match(reg);
            if(r!=null)return  unescape(r[2]); return null;
        }
    
        // 探测浏览器是否支持localStorage
        var isSupportLocalStorage = function() {
            try {
                return 'localStorage' in window && window['localStorage'] != null;
            } catch (e) {
                return false;
            }
        };
    
        var addEvent = (function() {
            if(document.addEventListener) {
                return function(el, type, fn) {
                    if(el && el.nodeName || el === window) {
                        el.addEventListener(type, fn, false);
                    } else if (el && el.length) {
                        for(var i = 0; i < el.length; i++) {
                            addEvent(el[i], type, fn);
                        }
                    }
                };
            } else {
                return function(el, type, fn) {
                    if(el && el.nodeName || el === window) {
                        el.attachEvent('on' + type, function() {
                            return fn.call(el, window.event);
                        });
                    } else if (el && el.length) {
                        for(var i = 0; i < el.length; i++) {
                            addEvent(el[i], type, fn);
                        }
                    }
                };
            }
        })();
    
        var play=document.getElementById('play');
        if(isSupportLocalStorage()) {
            // 清除所有存储的key,value值
            localStorage.clear();
            var playBtn = document.getElementById('play');
            addEvent(playBtn, 'click', function () {
            // 按下按钮存下当前输入框中的值
                localStorage.setItem('rid', getQueryString('rid'));
            }); 
        
            // 存储数字
            //localStorage.setItem('number', 1);
            // 存储对象 因为localStorage最终都是以String来存储的  所以如果要存储对象 可以覆写它的toString方法
            // 按照你想要的字符串格式来存储, 然后取出后再做相应的处理, 这里就拿json格式做个例子
            //localStorage.setItem('obj', "{'name':'Andrew', 'job': 'Developer'}");
            // 常规的存储
            //localStorage.setItem('string', 'hello world');
    
        } else {
            // 这里可以做些降级的方案, 当然也可以给出一个不支持的提示
            var span = document.createElement("span");
            span.style.color = 'red';
            span.innerHTML = 'oops, your browser dones\'t support localStorage yet. :(';
            document.getElementsByTagName('body')[0].appendChild(span);
        }
    </script>
    </html>
    
    <!-- new.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>这是新的页面</title>
    </head>
    <body>
        <p id="p"></p>
        <table border="1px">
            <tr>
                <td>房间号</td>
                <td>消息</td>
            </tr>
            <tr id="101">
                <td name="rid">101</td>
                <td name="msg">暂无</td>
            </tr>
            <tr id="102">
                <td name="rid">102</td>
                <td name="msg">暂无</td>
            </tr>
            <tr id="103">
                <td name="rid">103</td>
                <td name="msg">暂无</td>
            </tr>
        </table>
    </body>
    <script type="text/javascript">
        // 探测浏览器是否支持localStorage
        var isSupportLocalStorage = function() {
            try {
                return 'localStorage' in window && window['localStorage'] != null;
            } catch (e) {
                return false;
            }
        };
    
        var addEvent = (function() {
            if(document.addEventListener) {
                return function(el, type, fn) {
                    if(el && el.nodeName || el === window) {
                        el.addEventListener(type, fn, false);
                    } else if (el && el.length) {
                        for(var i = 0; i < el.length; i++) {
                            addEvent(el[i], type, fn);
                        }
                    }
                };
            } else {
                return function(el, type, fn) {
                    if(el && el.nodeName || el === window) {
                        el.attachEvent('on' + type, function() {
                            return fn.call(el, window.event);
                        });
                    } else if (el && el.length) {
                        for(var i = 0; i < el.length; i++) {
                            addEvent(el[i], type, fn);
                        }
                    }
                };
            }
        })();
    
        if(isSupportLocalStorage()) {
            // 给window监听storage事件
            addEvent(window, 'storage', function (event) {
                // 查看event对象内容
                // console.dir(event);
                // 可以输出oldValue和newValue观察
                changeMsg(event.newValue);
                console.log('key: %s, old value: %s, new value: %s', event.key, event.oldValue, event.newValue);
            });
        
        // 取出来也是String类型的, 要用parseInt转换下
        //console.log(parseInt(localStorage.getItem('number')));
        // 取出来的json格式字符串要用eval解析一下 转换成对象
        //console.dir(eval('(' + localStorage.getItem('obj') + ")"));
        // 普通的读取
        //console.log(localStorage.getItem('string'));
        
        } else {
            var span = document.createElement("span");
            span.style.color = 'red';
            span.innerHTML = 'oops, your browser dones\'t support localStorage yet. :(';
            document.getElementsByTagName('body')[0].appendChild(span);
        }
    
        function changeMsg(rid){
            var obj=document.getElementById(rid);
            obj.cells[1].innerHTML='有人点播了哦';
        }
    </script>
    </html>
    

    相关文章

      网友评论

        本文标题:Storage事件监听

        本文链接:https://www.haomeiwen.com/subject/mkhbbxtx.html