Benefit of CORS over cross-domain messaging

前端 未结 3 742
抹茶落季
抹茶落季 2020-12-17 01:20

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?

3条回答
  •  悲哀的现实
    2020-12-17 02:18

    I believe the spirit of the question was "for doing cross-domain XHR, what are the relative merits and disadvantages of CORS and an iframe+postMessage-based approach?"

    Explaining what they are intended for doesn't really help answer that question.

    Here I try to answer the question, from the perspective of a service provider who wants to provide "services" (data, behavior) to specific known pages/domains, and needs those domains to be able to "call in" to it.

    CORS

    • Pros
      • Easy to understand when it works / super-easy on the client (doesn't require any complex logic, a simple XmlHttpRequest/fetch call will do the trick)
    • Cons
      • Performance: Up-front round-trip overhead for every new URL (and previously visited one after CORS authorization has expired)
      • Potentially complex / often misunderstood implementation server-side (designating when CORS should should be allowed, handling a specialized verb, etc)
      • Very slightly lower support coverage across browsers (than postMessage): https://caniuse.com/#feat=cors vs https://caniuse.com/#feat=x-doc-messaging

    iframe+postMessage

    • Pros
      • SameSite cookie handling is not a problem (the thing that crosses the domain boundary is the postMessage call, not the XHR call)
      • Simple server-side implementation (just host a "page" containing your JS code and cross-domain messaging rules; most of the complexity ends up in front-end JS)
    • Cons
      • More work on the client; if you provide a service, instead of providing a simple endpoint, you need to deliver an "SDK", a script to be executed in the target page.
      • Potentially complex / often misunderstood implementation client-side (specifying what origins should be allowed to post to you, etc)
      • Possibly higher impact when processing a big message than a big XHR payload arriving?? https://dassur.ma/things/is-postmessage-slow/
      • Potential complexities if you set "X-Frame-Options" to help secure your (service-providing) site - you need to add an exemption for the messaging iframe host "page".

    (please adjust/correct/add!)

提交回复
热议问题