davidjbradshaw / iframe-resizer

Keep iFrames sized to their content.
https://iframe-resizer.com
Other
6.66k stars 981 forks source link

Multiple targetOrigin #707

Open wei2go opened 5 years ago

wei2go commented 5 years ago

Is there a way to restricted multiple 'targetOrigin' on an iFramed page, instead of just default it to '*', or restricted to only one domain?

davidjbradshaw commented 5 years ago

This is passed to window.postMessage, so is restricted to what the browser supports

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

FortinFred commented 5 years ago

@davidjbradshaw

I think there's two aspects to consider regarding messages.

Message reception:

function receiveMessage(event)
{
  // Here we might want to trust multiple origins
  if (event.origin !== "http://example.com" && event.origin !== "http://someothertrustedorigin.com")
    return;
}
window.addEventListener("message", receiveMessage, false);

Sending a message back: In this case, given that you have received at least one message from the parent, you could store the event.origin and use it for sending messages from frame to parent.

IMHO, targetOrigin should be renamed to trustedOrigins. The target would always be the parent that included the frame which is provided in event.origin

function receiveMessage(event)
{
  // Do we trust the event's origin
  if ( ! trustedOrigins.includes(event.origin) )
    return;

  // event.source is window.opener
  // event.data is "hello there!"

  // Assuming you've verified the origin of the received message (which
  // you must do in any case), a convenient idiom for replying to a
  // message is to call postMessage on event.source and provide
  // event.origin as the targetOrigin.
  event.source.postMessage("hi there yourself!  the secret response " +
                           "is: rheeeeet!",
                           event.origin);
}

window.addEventListener("message", receiveMessage, false);
jackrabbithanna commented 3 years ago

Was it decided that this was possible with this library? A simple use case would be wanting to allow 3 domains, for dev/staging/production domains, but no others.

menachemshapiro commented 2 years ago

I'm pretty much looking for exactly this option. Any update to whether it is possible?

davidjbradshaw commented 3 months ago

I've been looking at this and the issue is that you end up flooding the console with erroneous error messages. As every rejected postMessage call logs out an uncatchable error message.