跨域访问方法介绍(5)--使用 window.postMessage 传递数据

postMessage 是 HTML5 XMLHttpRequest Level 2 中的 API,能够用于窗口间消息的传递:页面和其打开的新窗口的数据传递、页面与嵌套的frame消息传递、页面与嵌套的iframe消息传递。本文主要介绍经过使用 postMessage 方法来实现不一样域下页面间的通讯,文中所使用到的软件版本:Chrome 90.0.4430.212。javascript

一、语法

1.一、发送消息

otherWindow.postMessage(message, targetOrigin, [transfer]);

otherWindow
其余窗口的一个引用,好比 iframe 的 contentWindow 属性、执行 window.open 返回的窗口对象、或者是命名过或数值索引的 window.frames。html

message
将要发送到其余 window的数据。它将会被结构化克隆算法序列化。这意味着你能够不受什么限制的将数据对象安全的传送给目标窗口而无需本身序列化。java

targetOrigin
经过窗口的 origin 属性来指定哪些窗口能接收到消息事件,其值能够是字符串 "*"(表示无限制)或者一个URI。在发送消息的时候,若是目标窗口的协议、主机地址或端口这三者的任意一项不匹配 targetOrigin 提供的值,那么消息就不会被发送;只有三者彻底匹配,消息才会被发送。这个机制用来控制消息能够发送到哪些窗口;例如,当用 postMessage 传送密码时,这个参数就显得尤其重要,必须保证它的值与这条包含密码的信息的预期接受者的 origin 属性彻底一致,来防止密码被恶意的第三方截获。若是你明确的知道消息应该发送到哪一个窗口,那么请始终提供一个有确切值的 targetOrigin,而不是*。不提供确切的目标将致使数据泄露到任何对数据感兴趣的恶意站点。web

transfer(可选)
是一串和 message 同时传递的 Transferable 对象。这些对象的全部权将被转移给消息的接收方,而发送一方将再也不保有全部权。算法

1.二、接受消息

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {
  if (event.origin !== "http://example.org:8080") {
    return;
  }

  //...
}

event 的属性有:tomcat

data
从其余 window 中传递过来的对象。安全

origin
调用 postMessage 时消息发送方窗口的 origin。app

source
对发送消息的窗口对象的引用; 您可使用此来在具备不一样 origin 的两个窗口之间创建双向通讯。webapp

二、样例

在 http://a.com:8080/a.html 打开 http://b.com:8080/b.html,而后在 a.html 给 b.html 页面发送消息,b.html 回消息给 a.html。post

2.一、模拟域名访问

在 C:\Windows\System32\drivers\etc\hosts 文件中增长:

127.0.0.1 a.com
127.0.0.1 b.com

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.三、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.四、部署访问

把 a.html 和 b.html 放到 tomcat 的 webapps\ROOT 下,访问地址为:http://a.com:8080/a.html。

相关文章
相关标签/搜索