Let’s say you have two websites in different domains, where the customer access the dominio1.com
and it has an iframe pointed to the dominio2.com
.
For the domain dominio2.com
send a message to dominio1.com
it is necessary to use the method .postMessage()
var outraJanela = window.parent;
var data = { ... }; //objeto que será enviado;
var json = JSON.stringify(data);
outraJanela.postMessage(json, "http://dominio1.com");
note that we specify the domain that will be targeted, this is to prevent your domain from communicating with unwanted domains, for example dominio-falso.com
.
now in dominio1.com
you need to add a Reader to receive the message sent by dominio2.com
window.addEventListener("message", function (event) {
if (event.origin === "http://dominio2.com") {
var data = JSON.parse(event.data); // os dados enviados por dominio2
}
});
Once again it is necessary to check who sent the message, so we verify that the origin is the expected one, in case dominio2.com
.
if you need to send a confimation message to dominio2.com
, just do the following:
window.addEventListener("message", function (event) {
if (event.origin === "http://dominio2.com") {
var data = JSON.parse(event.data); // os dados enviados por dominio2
event.source.postMessage("OK", event.origin);
}
});
remembering that we will need to add window.addEventListener("message", ...)
in dominio2.com
so that he can receive the confimation message.
The page inside the iframe is in the same domain?
– Sergio
No, they’re on different domains and servers
– sNniffer
Then I suggest you use JSONP, if both pages are yours and you have access to a server language.
– Sergio