Do I Understand CORS
I need to do a test for Cannon, and this might as well be a mini-article to understand cross-origin iframe access. The main question I have is:
Are iframe’s considered same-origin when I host them on Cloudflare Pages under different subdomains?
Some useful background:
- Cross-origin iframe access seems to be completely disallowed, you have to communicate using
postMessage
. This is regardless of any CORS headers the page sends. - An “origin” is a combination of (protocol, domain, port).
I was tearing my head out trying to understand this locally, but I realized the easier thing to do is just try it on two subdomains I have active: blog.cryingpotato.com
and aods.cryingpotato.com
. I’ll do a full article later on Advent of Distributed Systems (the iframe embedded below), but right now, we’re going to find out together if I’m able to access this iframe’s data below. After embedding the iframe, I have a simple React component that does this:
try {
iframeContent = iframe.contentWindow!.document.body.outerHTML.slice(0, 100);
} catch (e) {
iframeContent = `Could not parse content: ${e}`;
}
and renders the result.
Just for completion, I also included a definitely same-origin iframe where I can access the data on localhost
. The other iframe is inaccessible on localhost because the origin doesn’t match.
I’ll only be able to tell if I can access this data once I deploy (I could probably do some shennanigans with /etc/hosts
to figure this out also, but why bother). Let’s see if I understand CORS! My prediction is that the body should load in both cases.
Update
I did not understand CORS, the domain
did indeed include the subdomain. This is particularly annoying for hosting the sandpack bundler myself, which I need to do in order to access the content of the underlying iframe for a secret project I’m cooking up. Ah well, back to beating my head against a wall to get Sandpack to work against localhost:5173/sandpack
. If you’re curious why we can’t access different subdomains across iframes, this issue is a good place to start. A more thorough overview of web security is available here.