Let's say you have two sites in different domains, where the client accesses dominio1.com
and it has an iFrame pointed to dominio2.com
.
For the domain dominio2.com
send a message to the 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 the target, this is to prevent your domain from communicating with unwanted domains, such as dominio-falso.com
.
Now in dominio1.com
you need to add a listener to get 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 verify who sent the message, so we found that the origin is the expected one, in the case dominio2.com
.
If you need to send a confirmation 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 you need to add window.addEventListener("message", ...)
to dominio2.com
so that it can receive the config message.