Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit of CORS over cross-domain messaging

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?

like image 295
Christophe Avatar asked Nov 18 '11 17:11

Christophe


2 Answers

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

like image 95
Esailija Avatar answered Sep 27 '22 17:09

Esailija


First of all you should be aware that CORS is supported by the following browsers: Internet Explorer 8+, Firefox 3.5+, Safari 4+, and Chrome. Please note that IE7 and older versions of Firefox and Safari doesn't support it at all. But event IE8 has some limitations - it doesn't support credentials and "preflight" requests to be sent to the server. In addition, your server should be ready for CORS requests, i.e. some extra work on the server should be performed as well.

Cross-domain messaging by using JSONP or iFrames are more universal in terms of browser support and sometimes even doesn't require extra server-side work.

like image 21
Pavel Podlipensky Avatar answered Sep 27 '22 18:09

Pavel Podlipensky