瀏覽器內多標籤通訊

實現瀏覽器內多標籤通訊有多種方法, 可使用WebSocket、SharedWorker;也能夠調用localstorge、cookies等本地存儲方式;這裏介紹使用localStorage方法實現。javascript

#####使用 localStorage實現瀏覽器內多標籤通訊 localstorge在一個標籤頁裏被添加、修改或刪除時,都會觸發一個storage事件,經過在另外一個標籤頁裏監聽storage事件,便可獲得localstorge存儲的值,實現不一樣標籤頁之間的通訊。css

下面的例子是由b頁面監聽a頁面的事件變化並記錄html

//a.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>瀏覽器內多頁面通訊 </title>

    <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(function(){
            $("#btn").click(function(){
                var name=$("#name").val();
                localStorage.setItem("name", name); //存儲數據
            });
        });
    </script>

</head>
<body>
<input id="name">
<input type="button" id="btn" value="提交">


</body>
</html>
複製代碼

頁面a中只有一個輸入框和一個提交按鈕,當點擊提交後,用localStorage.setItem進行數據存儲java

//b.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(function(){
            window.addEventListener("storage", function(event){
                console.log(event.key + "=" + event.newValue);
            });
        });
    </script>

</head>
<body>
</body>
</html>
複製代碼

b頁面中使用addEventListener進行事件監聽,輸出事件信息jquery

#####實現效果: 瀏覽器

a

b
相關文章
相關標籤/搜索