首页 >web前端 >js教程 > 正文

有关js页面间通信方法storage事件的介绍

原创2017-10-26 09:45:411043

  在写页面的时候有时会遇到这样的需求,需要两个页面之间传递数据或者一个事件。这个时候,就需要用到我今天所要讲的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('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>
登录后复制

以上就是有关js页面间通信方法storage事件的介绍的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

  • 相关标签:javascript storage 方法
  • 相关文章

    相关视频


    视频教程分类

    专题推荐