CORS对跨域消息传递的好处 [英] Benefit of CORS over cross-domain messaging

查看:184
本文介绍了CORS对跨域消息传递的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CORS 和跨网域邮件看起来与我一样:它们允许跨域通信。


解决方案

CORS是对于闪存通常不允许的ajax请求或闪存请求。例如,如果没有域x的跨域策略,并且您通过闪存检索mp3文件进行播放,则Flash不会允许您读取mp3文件的id3标签。对于ajax,如果目标服务器没有允许您的域提出请求的跨域策略,则无法发出请求。



跨域邮件允许您与来自不同来源的文档中的iframe进行通信。例如,如果您有YouTube视频iframe,则可以向该iframe传递一条消息以更改音量。通常,不能进行通信,因为iframe具有不同的来源,因此您无法以编程方式对youtube iframe执行任何操作。



使用一个或另一个,现在应该清楚。 CORS允许您从其他来源请求数据,而当您要与位于iframe内但不在同一来源的应用进行通信时,在主窗口和iframe之间传递消息时使用。



一个实际的例子:



1.您有一个有youtube播放器的iframe。



2.您要求一些视频从YouTube数据API(CORS,可以是JSONP,XHR或其他任何内容)播放。



3.您现在通过跨网域消息发送到iframe,以开始播放您在第#2步请求的任何视频


CORS and cross-domain messaging look the same to me: they allow communication across domains.

Are there any reasons to use one vs. the other?

解决方案

CORS is for ajax requests or flash requests that flash wouldn't normally allow. For example, if there is no cross-domain policy for domain x, and you retrieve an mp3 file from there via flash for playback, flash will not allow you to read the id3 tags of the mp3 file. For ajax, you flat out cannot make the request if the target server doesn't have a cross-domain policy that allows your domain to make requests.

Cross-domain messaging allows you to communicate with an iframe in the document that is from different origin. For example, if you have youtube video iframe, you may pass a message to that iframe to change volume. Normally no communication wouldn't be possible because the iframe has a different origin, so you could not do anything with the youtube iframe programmatically.

The reasons to use one or another, should be now clear. CORS allows you to request data from another origin while message passing between main window and an iframe is used when you want to communicate with an app that is inside the iframe but is not in the same origin.

A practical example:

1.You have an iframe that has a youtube player.

2.You request some videos to play from youtube data api (CORS, could be JSONP, XHR or whatever).

3.You now pass a cross-domain message to the iframe to start playing any of the video you requested in step #2

这篇关于CORS对跨域消息传递的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆