首页 > Web开发 > 详细

js页面间通信方法实现

时间:2019-08-29 11:34:58      阅读:94      评论:0      收藏:0      [点我收藏+]

  在写页面的时候经常会碰到这样的需求:需要两个打开着的页面间传递数据或者事件。

  比如:已有列表页A,通过A打开详情B进行编辑;编辑保存之后希望A能自动刷新页面。这个时候就可以用到“storage”事件。关于localStorage的用法可在其他地方找到。

  可触发“storage”事件的条件如下:

  同一个浏览器打开了多个同源的页面(URL由协议、域名、端口和路径组成,如果两个URL的协议、域名和端口相同,则表示他们同源);

  一个网页中修改localStorage

  另一个网页注册了storage事件

http://www.cnblogs.cn/demo/index.html

//这个网址,协议是http://域名是www.cnblogs.cn,端口是80(默认端口可以省略)


//对比URL:

http://www.cnblogs.cn/demo2/other.html     //同源

http://www.cnblogs.cn:81/demo/index.html   //不同源

http://sxh.cnblogs.cn/demo/index.html      //不同源

http://www.pudn.cn/demo/index.html         //不同源

  在测试的时候,一定要保证是同源页面。

  下面是页面间交互代码,实现非常简单,pageA和pageB之间通信。

pageA:添加“storage”监听

<!DOCTYPE html>

<html>

<head>

    <title>page A</title>

</head>

<body>

<script>

    window.addEventListener("storage", function (e) {

        console.log(e)

        console.log(e.newValue)

    });

</script>

</body>

</html>

pageB:设置localStorage

<!DOCTYPE html>

<html>

<head>

<title>page B</title>

</head>

<body>

<button>click<button>

</body>

<script>

      document.querySelector(button).onclick = function(){
        //留意random,若Refresh的值未做变更,则不会触发A页面的“storage”事件
              localStorage.setItem(‘Refresh, Math.random()*10);

      }

</script>

</html>

 

  

js页面间通信方法实现

原文:https://www.cnblogs.com/zran/p/11428158.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!