首頁  >  文章  >  web前端  >  有關js頁間通訊方法storage事件的介紹

有關js頁間通訊方法storage事件的介紹

一个新手
一个新手原創
2017-10-26 09:45:411486瀏覽

  在寫頁面的時候有時會遇到這樣的需求,需要兩個頁面之間傳遞資料或一個事件。這時候,就需要用到我今天所要講的storage事件,學習這個事件之前,需要先了解localStorage的用法。具體用法可以查看其他文件。出發storage事件的條件如下:

  1. 同一個瀏覽器開啟了兩個同源的頁面

  2. 一個網頁中修改localStorage

  3. 另一網頁註冊了storage事件

  #storage事件,只有在同源頁下,才有作用,不同源是沒有作用的。那什麼是同源呢?

  URL由協定、網域名稱、連接埠和路徑組成,如果兩個URL的協定、網域名稱和連接埠相同,則表示他們同源。舉個栗子:


http://www.wszdaodao.cn/demo/index.html
//这个网址,协议是http://域名是www.wszdaodao.cn,端口是80(默认端口可以省略)

//对比URL:
http://www.wszdaodao.cn/demo2/other.html     //同源
http://www.wszdaodao.cn:81/demo/index.html   //不同源
http://sxh.wszdaodao.cn/demo/index.html      //不同源
http://www.mamama.cn/demo/index.html         //不同源

  所以在測試時候,一定要保證是同源頁。

  下面是兩個頁間互動程式碼,實作非常簡單,pageA與pageB之間通訊。

page A : 設定localStorage


#
<!DOCTYPE html>
<html>
<head>
<title>page A</title>
</head>
<body>
<button>click<button>
</body>
<script>
      document.querySelector(&#39;button&#39;).onclick = function(){
              localStorage.setItem(&#39;Num&#39;, Math.random()*10);
      }
</script>
</html>

page B:監聽storage事件


<!DOCTYPE html>
<html>
<head>
    <title>page B</title>
</head>
<body>
<script>
    window.addEventListener("storage", function (e) {
        console.log(e)
        console.log(e.newValue)
    });
</script>
</body>
</html>

以上是有關js頁間通訊方法storage事件的介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn