HTML5跨文档消息传递

HTML5定义了一些javascript API,其中有一个就是跨文档消息传递(cross-document-messaging简称XDM)。 现在XDM已经作为一个规范独立了出来,名字为:Web Messaging   项目地址为:http://dev.w3.org/html5/postmsg/ XMD核心就是postMessage()方法,这个方法接受两个参数一个是需要传送的字符串,第二个是接收方的域的字符串。 第二个参数可以控制一定的安全性,如果把第二个参数设置为"*",那么就是所有的域都可以接收此消息。 而相对于postMessage()方法的其他页面指的就是包含在当前页面中的<iframe>元素或者是由当前窗口弹出的窗口。如下列中首先创建一个iframe内嵌框架,获取iframe元素window对象的引用(所有支持XDM的浏览器都支持iframe的contentWindow属性),然后进行消息传递。

 1 var newIframe = document.createElement("iframe");

 2 

 3 newIframe.src = "http://www.baidu.com/";

 4 

 5 newIframe.width = "500px";

 6 

 7 newIframe.height = "500px";

 8 

 9 document.body.appendChild(newIframe);

10 

11 var iframeWindow = newIframe.contentWindow;

12 

13 iframeWindow.postMessage("this is post mess", "http://www.baidu.com");     //传递信息成功

 

传递过后会触发接收方window对象的message事件,在message事件对象中包含三个息息相关重要的属性:

  • data:里面包含由postMessage()方法传递过来的第一个参数信息,也就是传递的消息,为字符串形式
  • origin:发送消息的方的域,字符串形式如:“http://www.baidu.com”
  • source:发送消息方的window对象代理,这个代理主要用于在接收到消息过后然后反馈给发送方消息,调用方式同样为:event.source.postMessage("已收到消息","http://www.baidu.com"),但是它不能用于访问发送方文档信息。

用上面的例子来做演示:

 1 var newIframe = document.createElement("iframe");

 2 

 3 newIframe.src = "http://www.baidu.com/";

 4 

 5 newIframe.width = "500px";

 6 

 7 newIframe.height = "500px";

 8 

 9 document.body.appendChild(newIframe);

10 

11 var iframeWindow = newIframe.contentWindow;

12 

13 //定义接收方window对象的message事件

14 iframeWindow.addEventListener("message", function(event) { 

15 

16     //检查是否为安全域

17     if(event.origin == "http://www.baidu.com/") {  

18      

19          //弹出 “this is post mess”

20         alert(event.data);   

21 

22          //获取发送方的window代理并返回消息。域为baidu.com

23         event.source.postMessage("已收到消息,反馈","http://www.baidu.com/")    

24 

25     }; 

26 

27 }, false);  

28 

29 //定义发送方window对象的message事件

30 window.addEventListener("message", function(event) { 

31 

32     //检查是否为安全域

33     if(event.origin == "http://www.baidu.com/"){

34 

35          //弹出“已收到消息,反馈”

36         alert(event.data);   

37     }; 

38 

39 }, false);

40 

41 //传递信息成功 

42 iframeWindow.postMessage("this is post mess","http://www.baidu.com");   

43     

 

你可能感兴趣的:(html5)