JavaScript 跨域:window.postMessage 实现跨域通信

    JavaScript 跨域方式实现方式有很多,之前,一篇文章中提到了 JSONP 形式实现跨域。本文将介绍 HTML5 新增的 api 实现跨域:window.postMessage 。

  

 1 otherWindow.postMessage(message, targetOrigin);
 2 
 3 otherWindow
 4 其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。
 5 
 6 message
 7 将要发送到其他 window的数据。将会被结构化克隆算法序列化。这意味着你可不受什么限制的安全传送数据对象给目标窗口而无需自己序列化。
 8 
 9 targetOrigin
10 该参数可设置为 *,将无域名限制。也可指定特定的域名,比如:http://www.jj.com
11 
12 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

 

    本文还是以 iframe 为例,一个 html 页面中套有一个 iframe 文档,不过,iframe 文档 src 属性与 html 页面不同域,因此,两者之间便形成跨域。

 

     index.html _http://localhost:3127/index.htm 

<!DOCTYPE html >
<html >
<head>
    <title></title>
</head>
<body >
   <input type="text"  id="val"/>
    <input type="button" id="btn" value="测试" /><br/>
    
    <iframe src="http://localhost:10528/index.html" > </iframe>
    <script type="text/javascript">
        window.onload = function () {
// 首先,给按钮绑定 click 事件
if (window.addEventListener)
document.getElementById(
'btn').addEventListener('click', sendMsg, false); else document.getElementById('btn').attachEvent("onclick", sendMsg); };
// 获取 iframe 标签,利用 postMessage 跨域通信,值为 input text 标签值
function sendMsg() { document.getElementsByTagName('iframe')[0].contentWindow.postMessage(document.getElementById('val').value,"*"); } </script> </body> </html>

 

  index.html (iframe) _http://localhost:10528/index.html

<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

</head>
<body >
   <b>我是另一个跨中 iframe 文档</b>
    <script type="text/javascript">

// 给 iframe 文档绑定 message 事件 window.onload = function () { if (window.addEventListener) window.addEventListener('message', getMessage, false); else window.attachEvent("onmessage", getMessage); };
// iframe 触发 message 事件时,调用 getMessage 函数
function getMessage(event) { console.dir(event); alert(event.data); } </script> </body> </html>


 

参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

posted @ 2016-05-18 15:07  Lumia1020  阅读(928)  评论(0编辑  收藏  举报