HTML5的window.postMessage API

I've create a MooTools plugin to wrap window.postMessage: PostMessager. Click here to download it!

我已经创建了一个MooTools插件来包装window.postMessage:PostMessager。 点击这里下载!

HTML5 window.postMessage

One of the little known HTML5 APIs is the window.postMessage API.  window.postMessage allows for sending data messages between two windows/frames across domains.  Essentially window.postMessage acts as cross-domain AJAX without the server shims. Let's take a look at how window.postMessage works and how you can use it today in Firefox, IE8+, Opera, Safari, and Chrome.

window.postMessage API是鲜为人知HTML5 API之一window.postMessage允许在跨域的两个窗口/框架之间发送数据消息。 本质上,window.postMessage充当跨域AJAX,而无需服务器填充。 让我们看看window.postMessage工作原理以及如何在Firefox,IE8 +,Opera,Safari和Chrome中使用它。

第一部分:发件人 (Part One:  The Sender)

The first part of the process is setting up a "source".  With the source, we will open a new window (or IFrame, if you'd prefer to), send the new window message (for the sake of our example, we'll do so every 6 seconds, and create an event listener for any response we receive from the destination window.

该过程的第一部分是设置“源”。 使用源,我们将打开一个新窗口(或IFrame,如果您愿意),发送新的窗口消息(就我们的示例而言,我们每6秒钟发送一次,并为该事件创建一个事件侦听器我们从目标窗口收到的任何响应。


//create popup window
var domain = 'http://scriptandstyle.com';
var myPopup = window.open(domain + '/windowPostMessageListener.html','myWindow');

//periodical message sender
setInterval(function(){
	var message = 'Hello!  The time is: ' + (new Date().getTime());
	console.log('blog.local:  sending message:  ' + message);
	myPopup.postMessage(message,domain); //send the message and target URI
},6000);

//listen to holla back
window.addEventListener('message',function(event) {
	if(event.origin !== 'http://scriptandstyle.com') return;
	console.log('received response:  ',event.data);
},false);


I've used window.addEventListener which doesn't work with Internet Explorer (IE uses window.attachEvent). You'll want to use a function to normalize event assignment or use MooTools/jQuery/Dojo to do so.

我使用过的window.addEventListener不适用于Internet Explorer(IE使用window.attachEvent )。 您将要使用函数来规范事件分配,或使用MooTools / jQuery / Dojo来做到这一点。

Assuming the window opened properly, we send a message and specified URI match (protocol, hostname, and port, if present) that the destination window must currently be at (because the user may have changed the address of that subsequent window).  If the destination window has changed, the message will not be sent.

假设窗口正确打开 ,我们发送一条消息并指定目标窗口当前必须位于的URI匹配(协议,主机名和端口(如果存在))(因为用户可能已更改了该后续窗口的地址)。 如果目标窗口已更改,则不会发送该消息。

We've also created an event handler for receiving a message.  It's extremely important that you validate the event origin when receiving a message because the message handler accepts messages from any URI!  Once the origin is validated, you may handle the provided message in any way you'd like.

我们还创建了一个事件处理程序来接收消息。 接收消息时验证事件起源非常重要,因为消息处理程序会接受来自任何URI的消息! 验证来源之后,您可以按照任何方式处理所提供的消息。

Here's what this looks like when using an IFrame:

这是使用IFrame时的样子:


//create popup window
var domain = 'http://scriptandstyle.com';
var iframe = document.getElementById('myIFrame').contentWindow;

//periodical message sender
setInterval(function(){
	var message = 'Hello!  The time is: ' + (new Date().getTime());
	console.log('blog.local:  sending message:  ' + message);
	iframe.postMessage(message,domain); //send the message and target URI
},6000);


Be sure to access the IFrame's contentWindow property -- not just the node itself.

确保访问IFrame的contentWindow属性-而不仅仅是节点本身。

第二部分:目的地 (Part Two:  The Destination)

The second part of the process is getting the destination window ready.  The destination window features an event listener for the "message" event and should validate the message origin.  Again, message events are accepted from any location so it's extremely important that their origin is validated against a list of trusted origins.

该过程的第二部分是准备目标窗口。 目标窗口具有“消息”事件的事件侦听器,并应验证消息的来源。 同样,消息事件可以从任何位置接受,因此,根据可信任来源列表验证消息来源非常重要。


//respond to events
window.addEventListener('message',function(event) {
	if(event.origin !== 'https://davidwalsh.name') return;
	console.log('message received:  ' + event.data,event);
	event.source.postMessage('holla back youngin!',event.origin);
},false);


The sample above sends a response back to the sender to confirm that the message was sent.  There are important event properties:

上面的示例将响应发送回发送方,以确认消息已发送。 有重要的事件属性:

  • source - The source window/frame the message was sent from.

    source-发送消息的源窗口/框架。

  • origin - The URI (protocol, domain, and port, if provided) match the message was sent from.

    origin-源 (URI)(协议,域和端口,如果提供的话)与消息发送的来源相匹配。

  • data - The actual message sent from the source.

    数据 -从源发送的实际消息。

All three of these components are essential to the messaging system and its validation.

所有这三个组件对于消息传递系统及其验证都是必不可少的。

使用window.postMessage (Using window.postMessage)

Like every other web technology, there's obvious danger that this technology could get used improperly if the source is not validated properly; it's up to you to make your application secure. window.postMessage is like the PHP of JavaScript technologies in that regard (oh, snap!).  window.postMessage is cool though, no?

与其他所有Web技术一样,如果没有正确验证来源,则存在很明显的危险,即该技术可能无法正确使用。 确保您的应用程序安全是您的责任。 在这方面, window.postMessage类似于JavaScript技术PHP(哦,快点!)。 window.postMessage很酷,不是吗?

翻译自: https://davidwalsh.name/window-postmessage

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值