现在的位置: 首页 > 移动开发 > 正文

HTML5 Messaging方法有哪些

2020年06月08日 移动开发 ⁄ 共 1890字 ⁄ 字号 评论关闭

  HTML5的MessageAPI能够让HTML5页面之间传递消息,甚至这些页面可以不在同一样域名下。下面学步园小编来讲解下HTML5Messaging方法有哪些?

  HTML5Messaging方法有哪些

  发送消息

  为了让消息能从一个页面发送到另一个页面,主动发送消息的页面必须拥有另一个页面的窗口引用。然后发送页面针对接受页调用postMessage()方法。

  代码演示:

  1 varmessage="Hellothere";

  2 varorigin="http://www.oschina.net";

  3

  4 vartheIframe=document.getElementById("theIframe");

  5

  6 theIframe.contentWindow.postMessage(message,origin);

  postMessage()方法中origin参数的值必须与页面所在的iframe的域名相匹配。否则将无法正常运行,这里你不需要整个页面的网址,而只需要主域名就够了,例如http://localhost或http://www.oschina.net

  接受消息

  为了能接受消息,页面需要订阅好onmessage事件的处理方法,以下就是能在Firefox与Chrome上正常运行的代码:

  1 window.onmessage=function(event){

  2 document.getElementById("show").innerHTML=

  3 "MessageReceived:"+event.data

  4 +"from:"+event.origin;

  5 }

  以上代码设置好window的onmessage事件处理方法。然后在方法中找到id为"show"的html元素,然后设置此元素的innerHTML为"Messagereceived:"与真正的message。

  在IE9下必须以这种代码实现相同的功能。

  1 window.attachEvent("onmessage",function(event){

  2 document.getElementById("show").innerHTML=

  3 "MessageReceived:"+event.data

  4 +"from:"+event.origin;

  5 }

  建议你在JS中保持这两份代码,它们之间是没有冲突的。

  事件对象将包含以下三个属性。

  1 data

  2 origin

  3 source

  data属性包含包含发送页面发送过来的消息

  origin属性包含发送页面的原始域名

  source属性包含发送页面的window对象对应的引用。此window对象可以用来回复消息给原始的发送页面,只需要使用postMessage()就行,如下就是代码:

  HTML5Messaging方法有哪些

  1 window.onmessage=function(event){

  2 event.source.postMessage(

  3 "Thankyouforthemessage",

  4 event.origin

  5 );

  6 }

  发送JSON

  MessageingAPI只允许你发送字符串类型消息。如果你需要发送JavaScript对象,你将需要将此对象使用JSON.stringify()转换成JSON字符串,接受后使用JSON.parse()方法翻译成JavaScript对象。代码如下:

  1 vartheObject={property1:"hello",property2:"world"}

  2 varmessage=JSON.stringify(theObject);

  3 varorigin="http://tutorials.jenkov.com";

  4

  5 vartheIframe=document.getElementById("theIframe");

  6

  7 theIframe.contentWindow.postMessage(message,origin);

  以下代码就是如何将JSON字符串转换成JavaScript对象。

  1 window.onmessage=function(event){

  2 vartheObject=JSON.parse(event.data);

  3 }

  以上就是关于“HTML5Messaging方法有哪些”的内容,希望对大家有用。更多资讯请关注学步园。学步园,您学习IT技术的优质平台!

抱歉!评论已关闭.