問題描述
CORS 和跨域消息傳遞在我看來是一樣的:它們允許跨域通信.
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 適用于 Flash 通常不允許的 ajax 請求或 flash 請求.例如,如果域 x 沒有跨域策略,并且您通過 flash 從那里檢索 mp3 文件進(jìn)行播放,則 flash 將不允許您讀取 mp3 文件的 id3 標(biāo)簽.對于 ajax,如果目標(biāo)服務(wù)器沒有允許您的域發(fā)出請求的跨域策略,則您完全無法發(fā)出請求.
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.
跨域消息傳遞允許您與文檔中來自不同來源的 iframe 進(jìn)行通信.例如,如果您有 youtube 視頻 iframe,您可以向該 iframe 傳遞一條消息以更改音量.通常不可能進(jìn)行通信,因為 iframe 具有不同的來源,因此您無法以編程方式對 youtube iframe 執(zhí)行任何操作.
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.
現(xiàn)在應(yīng)該清楚使用一個或另一個的原因.CORS 允許您從另一個來源請求數(shù)據(jù),而當(dāng)您想與 iframe 內(nèi)但不在同一來源的應(yīng)用程序通信時,使用主窗口和 iframe 之間的消息傳遞.
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.
一個實際的例子:
1.您有一個帶有 youtube 播放器的 iframe.
1.You have an iframe that has a youtube player.
2.您請求從 youtube 數(shù)據(jù) api 播放一些視頻(CORS,可以是 JSONP、XHR 或其他).
2.You request some videos to play from youtube data api (CORS, could be JSONP, XHR or whatever).
3.您現(xiàn)在將跨域消息傳遞給 iframe 以開始播放您在第 2 步中請求的任何視頻
3.You now pass a cross-domain message to the iframe to start playing any of the video you requested in step #2
這篇關(guān)于CORS 對跨域消息傳遞的好處的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!