【9大跨域解决方案】postMessage解决跨域的原理

本文深入探讨H5中postMessage API的使用,讲解如何在不同文档、窗口及跨域间进行消息传递。覆盖基本语法、事件监听及实战案例,包括同源与跨域通信的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

postMessage()

这是H5引入的一个API,可以实现跨文档、多窗口、跨域消息的传递。

postMessage(data,origin)方法

  • data:要传递的数据
  • origin:字符串参数,只目标窗口的源,协议+主机+端口号[+URL],URL会被忽略,所以可以不写
  • 如果要传递给所有窗口,值可以为"*"
  • 如果传给当前窗口同源的话,值可以为"/"

message

当使用postMessage传递数据的时候,目标源可以使用message方法来接受传递过来的数据

message方法

 window.addEventListener('message',function(e){
  console.log(e.data);
 })
  • 该方法的参数e中有几个属性必须了解:
  1. e.data 指的是传递过来的数据
  2. e.origin 指的是发射源的域

实战举例

向同源发射信息(非跨域)

 window.postMessage('nihao','/'); 
 window.onmessage = function(e){
  console.log(e.origin);//当前源的域
  console.log(e.data);//传递过来的数据'nihao'
 }

跨域发送信息

  1. 先起两个服务,a.html起在localhost:3000上,b.html起在localhost:4000上
//a.html
<body>
 <iframe src="http://localhost:4000/b.html" frameborder="0" id="frame" "load()"></iframe>
 <script type="text/javascript">
  function load(){
   let frame = document.querySelector('#frame');
   console.log(frame);
   frame.contentWindow.postMessage('我叫俞华','http://localhost:4000')//向端口为4000的域发送内容"我叫俞华"
  }
  window.onmessage = function(e){
   console.log(e.data)
  }
 </script>
</body>

//b.html
<body>
 aaa
 <script type="text/javascript">
  window.onmessage = function(e){
   console.log('eeeeeeeee',e)
   console.log(e.data);
   //向父级(发射源)发送消息
   e.source.postMessage('你好','http://localhost:3000');
  }
 </script>
</body>

实现跨域的9种方法(点击可跳转详情页面)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值