Communicate to window from iframe on cross-domain

1.2k views Asked by At

Let's say I have have a webpage with domain name a.example.com which has an iframe with domain b.example.com (Not satisfying same origin policy).

Now I open a new window using window.open from the iframe with the same domain, that is b.example.com.

My task is to send message back to the iframe.

window.opener is empty for the opened window.

I read that I can communicate using postMessage, but to what element I should post the data to. How to get the reference of parent window (i.e the iframe).

2

There are 2 answers

3
Mike 'Pomax' Kamermans On

Who says the iframe is yours? The browser can't trust you in this respect because someone could be messing with your page and load something else instead, so modern browsers lock iframe communication down completely. Even with access control, you won't get two way communication going.

However, if you can make the iframe and the owning document "speak the same language", then you can use postMessage communication: postMessage basically posts strings (and only strings, so any JS objects need to be JSON.stringified) into a "visible to everyone" bucket of strings. Any document context can post messages, and every context can decide to listen to whether new messages are posted. If they are, then you can make the iframe send messages that the owning window can parse, and vice versa.

2
StackSlave On

In order to for their site, which holds the iframe that you control the contents of, to get information back from a window that is opened by clicking something within your contents, they have to allow access to your site on theirs. If you just want data from a window that is opened by clicking something on the page that you control it's like:

var newWindow = open('yourURL.php');
var someElement = newWindow.document.getElementById('someId');
console.log(someElement.value); // assuming it's an input

If you want information from the page that opened your other page from withing the newly opened window it's like:

var openerElement = opener.document.getElementById('openerWindowId');
console.log(openerElement.innerHTML); // assuming it's not an input