HTML5 window.postMessage与跨域讲解

作者:袖梨 2022-06-25

在前一篇文章中,讲到浏览器同源策略,即阻止不同域的页面间访问彼此的方法和属性,并对解决同源策略跨域问题提出的解决方案进行阐述:子域代理、JSONP、CORS。本篇将详细阐述HTML5 window.postMessage,借助postMessage API,文档间可以以安全可控的方式实现跨域通信,第三方JavaScript代码也可以与iframe内加载的外部文档进行通信。

HTML5 window.postMessage API

HTML5 window.postMessage是一个安全的、基于事件的消息API。

postMessage发送消息

在需要发送消息的源窗口调用postMessage方法即可发送消息。

源窗口

源窗口可以是全局的window对象,也可以是以下类型的窗口:

文档窗口中的iframe:

variframe = document.getElementById('my-iframe'); varwin = iframe.documentWindow;

JavaScript打开的弹窗:

varwin = window.open();

当前文档窗口的父窗口:

varwin = window.parent;

打开当前文档的窗口:

varwin = window.opener();

找到源window对象后,即可调用postMessage API向目标窗口发送消息:

``win.postMessage('Hello','ttp://jhssdemo.duapp.com/');```

postMessage函数接收两个参数:第一个为将要发送的消息,第二个为源窗口的源。

注:只有当目标窗口的源与postMessage函数中传入的源参数值匹配时,才能接收到消息。

接收postMessage消息

要想接收到之前源窗口通过postMessage发出的消息,只需要在目标窗口注册message事件并绑定事件监听函数,就可以在函数参数中获取消息。

window.onload =function() { vartext = document.getElementById('txt'); functionreceiveMsg(e) { console.log("Got a message!"); console.log("nMessage: "+ e.data); console.log("nOrigin: "+ e.origin); // console.log("Source: " + e.source); text.innerHTML ="Got a message!
"+ "Message: "+ e.data + "
Origin: "+ e.origin; } if(window.addEventListener) { //为窗口注册message事件,并绑定监听函数 window.addEventListener('message', receiveMsg,false); }else{ window.attachEvent('message', receiveMsg); } };

message事件监听函数接收一个参数,Event对象实例,该对象有三个属性:

  1. data 发送的具体消息

  2. origin 发送消息源

  3. source 发送消息窗口的window对象引用

说明

  1. 可以将postMessage函数第二个参数设为*,在发送跨域消息时会跳过对发送消息的源的检查。

  2. postMessage只能发送字符串信息。

实例

源窗口

Html5 postMessage open send

目标窗口win.html

Html5 postMessage

The New Window

相关文章

精彩推荐