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

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

  

 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 页面不一样域,所以,二者之间便造成跨域。html

 

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

<!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/postMessageapi

相关文章
相关标签/搜索