Capture Iframe input data

Asked

Viewed 236 times

0

Well, in a page I have an iframe, it is displayed part of the other site my, are on different servers, what I need is to access the iframe input and send to a variable javascript of my page, and by Iframe there is no way to send by Post or GET. From what I’ve read, browsers for security reasons don’t allow this, but I saw something related to HTML5 Post Messenger, but I couldn’t find any documentation or explain how it works.

Someone has already clarified and solved this problem?

  • The page inside the iframe is in the same domain?

  • No, they’re on different domains and servers

  • Then I suggest you use JSONP, if both pages are yours and you have access to a server language.

1 answer

0


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.