Capture input data Iframe

0

Well, in a page I have an iframe, it is displayed part of the other site of mine, they are in different servers, what I need is to access the input of the iframe and send to a javascript variable of my page, like sending by Post or GET. I've read some of the security browsers do not allow this, but I've seen something related to HTML5's Post Messenger, but I did not find any documentation or explain how it works.

Has anyone ever needed and solved this problem?

    
asked by anonymous 08.09.2015 / 20:56

1 answer

0

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.

    
08.09.2015 / 21:58