在写页面的时候有时会遇到这样的需求,需要两个页面之间传递数据或者一个事件。这个时候,就需要用到我今天所要讲的storage事件,学习这个事件之前,需要先了解localStorage的用法。具体用法可以查看其他文档。出发storage事件的条件如下:

  1. 同一个浏览器打开了两个同源的页面

  2. 一个网页中修改localStorage

  3. 另一网页注册了storage事件

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

  URL由协议、域名、端口和路径组成,如果两个URL的协议、域名和端口相同,则表示他们同源。举个栗子:


1  
2 //这个网址,协议是 
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

<!DOCTYPE html>
<html>
<head>
<title>page A</title>
</head>
<body>
<button>click<button>
</body>
<script>
      document.querySelector('button').onclick = function(){
              localStorage.setItem('Num', 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>
登录后复制


以上就是JavaScript页面间通信方法之storage事件详解的详细内容,更多请关注Work网其它相关文章!

09-17 23:34