js頁面間通信方法(storage事件)(瀏覽器頁面間通信方法)


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

  1. 同一個瀏覽器打開了兩個同源的頁面
  2. 一個網頁中修改localStorage
  3. 另一網頁注冊了storage事件

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

  URL由協議、域名、端口和路徑組成,如果兩個URL的協議、域名和端口相同,則表示他們同源。舉個栗子:

1 http://www.wszdaodao.cn/demo/index.html
2 //這個網址,協議是http://域名是www.wszdaodao.cn,端口是80(默認端口可以省略)
3 
4 //對比URL:
5 http://www.wszdaodao.cn/demo2/other.html     //同源
6 http://www.wszdaodao.cn:81/demo/index.html   //不同源
7 http://sxh.wszdaodao.cn/demo/index.html      //不同源
8 http://www.mamama.cn/demo/index.html         //不同源

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

  下面是兩頁面間交互代碼,實現非常簡單,pageA與pageB之間通信。

page A : 設置localStorage

 

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4 <title>page A</title>
 5 </head>
 6 <body>
 7 <button>click<button>
 8 </body>
 9 <script>
10       document.querySelector('button').onclick = function(){
11               localStorage.setItem('Num', Math.random()*10);
12       }
13 </script>
14 </html>

 

 

page B: 監聽storage事件

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <title>page B</title>
 5 </head>
 6 <body>
 7 <script>
 8     window.addEventListener("storage", function (e) {
 9         console.log(e)
10         console.log(e.newValue)
11     });
12 </script>
13 </body>
14 </html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM