(转)同一浏览器多个标签页之间的通信(一)——localStorage

一、localStorage

(1)localStorage是什么?

localStorage对象在修订过的HTML5规范中作为持久保存在客户端数据的方案取代了globalStorage,是Storage的实例。
!注意:要访问一个localStorage对象,页面必须来自同一个域名(子域名无效),使用同一种协议,在同一个端口上。相当于globalStorage[localhost.host]。

(2)localStorage怎么用?

localStorage作为Storage的实例,可以使用Storage实例的方法。
常见操作:

        localStorage.setItem('name','lwf');
        localStorage.age=21;//注意后填加的放在localStorage的前面
 
        console.log(localStorage.getItem('name'));//lwf
        console.log(localStorage.age);//21
        console.log(localStorage);//Storage {age: "21", name: "lwf", length: 2}
        console.log(localStorage.key(0));//age,注意index从0开始
 
 
        console.log(localStorage.length);//2
 
        localStorage.removeItem('name');
        console.log(localStorage.getItem('name'));//null
 
        localStorage.clear();
        console.log(localStorage);//Storage {length: 0}

(3)怎么使用localStorage实现多标签之间的通信?

index.html

 <input type="text">
    <button id="btn">Click</button>
    <script>
        window.onload=function(){
            var oBtn=document.getElementById("btn");
            var oInput=document.getElementsByTagName("input")[0];
            oBtn.onclick=function(){
                var val=oInput.value;
                localStorage.setItem("value",val);
            }
        }
    </script>

test.html

<script>
        window.addEventListener("storage",function(event){
            console.log("value is"+localStorage.getItem("value"));
            console.log("key is"+event.newValue);
        },false);    
    </script>

==================
注意:只能实现同一浏览器相同域名、相同协议、相同端口下的多个标签页之间的通信。不同浏览器没有该效果。
效果:

==================

(4)localStorage可以实现同一浏览器多个标签页之间通信的原理

localStorage是Storage对象的实例。对Storage对象进行任何修改,都会在文档上触发storage事件。当通过属性或者setItem()方法保存数据,使用delete操作符或removeItem()删除数据,或者调用clear()方法时,都会发生该事件。这个事件的event对象有以下属性:

*domin:发生变化的存储空间的域名;
*key:设置或者删除的键名;
*newValue:如果是设置值,则为新值;如果是删除值,则是null;
*oldValue:键被更改之前的值;

**注意:IE8和Firefox只实现了domin属性。 **

转自:https://blog.csdn.net/liwenfei123/article/details/79996161

posted @ 2018-11-12 22:56  人情冷暖i  阅读(1462)  评论(0编辑  收藏  举报