跨域访问方法介绍(5)--使用 window.postMessage 传递数据
postMessage 是 HTML5 XMLHttpRequest Level 2 中的 API,可以用于窗口间消息的传递:页面和其打开的新窗口的数据传递、页面与嵌套的frame消息传递、页面与嵌套的iframe消息传递。本文主要介绍通过使用 postMessage 方法来实现不同域下页面间的通信,文中所使用到的软件版本:Chrome 90.0.4430.212。
1、语法
1.1、发送消息
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow
其他窗口的一个引用,比如 iframe 的 contentWindow 属性、执行 window.open 返回的窗口对象、或者是命名过或数值索引的 window.frames。
message
将要发送到其他 window的数据。它将会被结构化克隆算法序列化。这意味着你可以不受什么限制的将数据对象安全的传送给目标窗口而无需自己序列化。
targetOrigin
通过窗口的 origin 属性来指定哪些窗口能接收到消息事件,其值可以是字符串 "*"(表示无限制)或者一个URI。在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配 targetOrigin 提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送。这个机制用来控制消息可以发送到哪些窗口;例如,当用 postMessage 传送密码时,这个参数就显得尤为重要,必须保证它的值与这条包含密码的信息的预期接受者的 origin 属性完全一致,来防止密码被恶意的第三方截获。如果你明确的知道消息应该发送到哪个窗口,那么请始终提供一个有确切值的 targetOrigin,而不是*。不提供确切的目标将导致数据泄露到任何对数据感兴趣的恶意站点。
transfer(可选)
是一串和 message 同时传递的 Transferable 对象。这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。
1.2、接受消息
window.addEventListener("message", receiveMessage, false); function receiveMessage(event) { if (event.origin !== "http://example.org:8080") { return; } //... }
event 的属性有:
data
从其他 window 中传递过来的对象。
origin
调用 postMessage 时消息发送方窗口的 origin。
source
对发送消息的窗口对象的引用; 您可以使用此来在具有不同 origin 的两个窗口之间建立双向通信。
2、样例
在 http://a.com:8080/a.html 打开 http://b.com:8080/b.html,然后在 a.html 给 b.html 页面发送消息,b.html 回消息给 a.html。
2.1、模拟域名访问
在 C:\Windows\System32\drivers\etc\hosts 文件中增加:
127.0.0.1 a.com 127.0.0.1 b.com
2.2、a.html
DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>父页面title>
<script type="text/javascript">
var child;
function openChild() {
child = window.open("http://b.com:8080/b.html");
}
function sendMessage() {
child.postMessage("该消息来自父页面", "http://b.com:8080");
}
function receiveMessage(event) {
if (event.origin !== "http://b.com:8080") {
alert(‘来源不可信:‘ + event.origin);
return;
}
alert(event.data);
}
window.addEventListener("message", receiveMessage, false);
script>
head>
<body>
<button onclick="openChild()">打开子页面button>
<button onclick="sendMessage()">发送消息到子页面button>
body>
html>
2.3、b.html
DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>子页面title>
<script type="text/javascript">
function receiveMessage(event) {
if (event.origin !== "http://a.com:8080") {
alert(‘来源不可信:‘ + event.origin);
return;
}
alert(event.data);
event.source.postMessage("该消息来自子页面", event.origin);
}
window.addEventListener("message", receiveMessage, false);
script>
head>
<body>
子页面
body>
html>
2.4、部署访问
把 a.html 和 b.html 放到 tomcat 的 webapps\ROOT 下,访问地址为:http://a.com:8080/a.html。
原文:https://www.cnblogs.com/wuyongyin/p/14835947.html