8

I have this code, I have set the MessageEvent 's origin to *, but still the console prompts Blocked a frame with origin "AAAA" from accessing a frame with origin "BBBB". Protocols, domains, and ports must match. Anyone know why?

  var size = {
    width:  document.body.scrollWidth,
    height:  document.body.scrollHeight
  }
  var evt = new MessageEvent("dimensionMessage",{
      "data": size,
      "origin":"*"
  });
  window.parent.dispatchEvent(evt);

However, if I use window.parent.postMessage(size, "*") , it works.

Blake
  • 7,367
  • 19
  • 54
  • 80
  • @Kaiido because I want a custom name for the receiver side. This code I placed in the external resource where the iframe `src` is referencing to. – Blake Aug 04 '16 at 05:54
  • @Kaiido they are on different domains, that's why I set `origin:"*"` in the first place – Blake Aug 04 '16 at 06:11
  • See also https://stackoverflow.com/questions/30183600/difference-between-custom-event-and-postmessage – Michael Freidgeim Jun 01 '22 at 20:50

2 Answers2

6

The error message tells you that a cross-origin iframe cannot in general invoke a method from the parent if it is in a different origin; that includes the dispatchEvent method (otherwise, an iframe could for instance generate mouse events in the parent page).

The postMessage API is an exception to that, designed precisely to allow cross-origin communication in a well-defined manner.

(Setting origin to '*' won't help you here; in general, that property is expected to be set by the browser when a message is sent via postMessage; creating manually a MessageEvent object is mostly only useful when you want to simulate in the receiving page the reception of an external message)

dontcallmedom
  • 2,420
  • 14
  • 12
  • Do note that event while using `"*"`, Cross-Origin Security Policies forbid the operation **if your using the file protocol (`file://`)**, unless you change setting in your browser or OS. – Cody Nov 16 '18 at 22:05
3

When two documents do not have the same origin, they have very limited access caused by Same-origin policy restrictions.

In your example dispatchEvent() has limited access to a different frame (window.parent).

window.postMessage() allow to perform a cross-window messaging avoiding Same-origin policy restriction.

Parameter targetOrigin for window.postMessage() specifies what the origin of otherWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a URI.

Please note that in your production code you should use a specific URI in order to make your code more secure. More information about how to use window.postMessage() securely can be found here https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

GibboK
  • 71,848
  • 143
  • 435
  • 658