1. Communcation API 介绍
通信(Communication)API是HTML5中用来实现正在运行的两个页面之间进行通信和信息共享的API,在开发Web应用程序时,其主要功能就是可以实现应用程序进程间通信。目前浏览器对其支持情况如下图:
2. Communcation API 运行流程
通信(Communication)API是HTML5中用来实现正在运行的两个页面之间进行通信和信息共享的API,
如上图所示,
Application在进行通信的时候被分为Host page(发送信息的页面),Client Page(接受信息的页面)。
Host page在发送信息的时候可以在代码中指定其信息为广播还是指定目标和端口进行发送。
发送之后,相应的接收端可以接收相同协议的Host page发送过来的消息。
当然,接收端有一个权限验证的过程,验证其消息来源于可信区域。
3. Communication API使用介绍
通信(Communication)API在HTML5中的使用的使用步骤主要分为三步,如下图所示:
从图中,大家可以看出如何写相应的代码。
在Host page端onSendMessage函数负责发送信息,并指定信息的发送方式:
function onSendMessage(e) {
//Loop through all the open windows and send the message
for( var d = 0; d < windows.length; d++){
windows[d].postMessage($( '#message' ).val(), 'http://localhost' );
windows[d].focus();
}
//Reset the textarea
$( '#message' ).val( '' );
}
//Loop through all the open windows and send the message
for( var d = 0; d < windows.length; d++){
windows[d].postMessage($( '#message' ).val(), 'http://localhost' );
windows[d].focus();
}
//Reset the textarea
$( '#message' ).val( '' );
}
在Client page端messageHandler函数来接收信息。
function messageHandler(e) {
//Check the origin of the message
switch(e.origin) {
//if it is the domain that we are listening from
case "http://experiments.72lions.com":
$( '#message').append( '<div>' + e.data + '</div>').css( 'display', 'block').stop().animate({opacity:1}, 200);
break;
default:
//Do nothing if the domain is not the one we are listening from
}
}
//Check the origin of the message
switch(e.origin) {
//if it is the domain that we are listening from
case "http://experiments.72lions.com":
$( '#message').append( '<div>' + e.data + '</div>').css( 'display', 'block').stop().animate({opacity:1}, 200);
break;
default:
//Do nothing if the domain is not the one we are listening from
}
}
运行结果如图所示。