Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...