I am developing a plugin (a React app) where I have two iframes (same domain) on a CORS site (different, i.e. client domain). Within this setup, I need to be able to communicate between:
- One iframe to another (same domain)
- iframe to client site (cross-domain)
For the second (cross-domain) case, I use the following code to deliver a message:
window.parent.postMessage(
message,
(new URL(document.referrer)).origin
)
which seems to work fine.
For the first (same domain) case, I use the following code:
const frames = window.parent.frames
for (let i = 0; i < frames.length; i++) {
frames[i].postMessage(
message,
window.origin
)
}
This also seems to work. However, in Safari (not in Chrome or Firefox) I get these error messages in the console:
Unable to post message to https://www.MY_DOMAIN.com. Recipient has origin https://www.SOME_OTHER_DOMAIN.com
The reason I'm blindly cycling through frames of the parent window is because I don't have a direct reference to my other iframe, and going deeper into the parent window to look for that iframe throws CORS errors... Like, for instance, this answer points out.
Is there a better way to target the recipient of the message? Or at least to avoid the errors in Safari console?
Thanks!