在写页面的时候有时会遇到这样的需求,需要两个页面之间传递数据或者一个事件。这个时候,就需要用到我今天所要讲的storage事件,学习这个事件之前,需要先了解localStorage的用法。具体用法可以查看其他文档。出发storage事件的条件如下:
- 同一个浏览器打开了两个同源的页面
- 一个网页中修改
localStorage
- 另一网页注册了
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>