iframe-resizer icon indicating copy to clipboard operation
iframe-resizer copied to clipboard

Multiple targetOrigin

Open wei2go opened this issue 6 years ago • 5 comments

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

wei2go avatar May 13 '19 06:05 wei2go

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

davidjbradshaw avatar May 14 '19 09:05 davidjbradshaw

@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);

FortinFred avatar Aug 29 '19 14:08 FortinFred

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.

jackrabbithanna avatar Oct 15 '20 19:10 jackrabbithanna

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

menachemshapiro avatar Jun 03 '22 06:06 menachemshapiro