How to use window.postMessage to dynamic embedded iframes?

1.3k views Asked by At

I am having multiple dynamic frames on my page. All the iframes are under the same domain. For example

<iframe src="data.php?id=1"> </iframe>
<iframe src="data.php?id=2"> </iframe>
<iframe src="data.php?id=3"> </iframe>

As you can see the iframes are linked to same page but with different id's.

So i am using a for loop to send the data to the iframe.(Code is below)

var iframes = document.getElementsByClassName('iframe');
for(var i = 0; i < iframes.length; i++)
{
    iframes[i].contentWindow.postMessage("getName","http://localhost/data.php");
}

I am not sure what to put in the origin parameter of the postMessage function (i.e the second parameter).

On the iframe i have this code to process the message.

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
    //event.source.postMessage("hi", event.origin);
    console.log('Message received');
}

But i didn't see anything in the console.

What's possibly is wrong??

Update

I found that instead of using postMessage I can also access the content in javascript functions. Now the problem is- I haven't figured a way how to accomplish this.

I want to access the textnode of the titleelement of the iframe by javascript.

1

There are 1 answers

0
David Bradshaw On BEST ANSWER

This will get the titles of your iFrames.

var iframes = document.getElementsByClassName('iframe');
for(var i = 0; i < iframes.length; i++){
    iframes[i].contentWindow.document.getElementsByTagName('title')[0].innerHTML;
}