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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With