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>
原文地址:https://www.cnblogs.com/wangEddy/p/7732675.html