Hubert Solecki
Hubert Solecki

Reputation: 2771

Issue communication with postMessage from parent to child iFrame

I'm having an issue communicating from my parent window to the child iFrame. But in the other side, everything works perfectly. Here is how I get the chil iFrame object in order to fire the postMessage function:

var iFrame = document.getElementById('Frame').contentWindow;

When I print it int he console, I get the following:

Window {parent: Window, opener: null, top: Window, length: 0, frames: Window…}

When I proceed to the postMessage function as follows:

iFrame.postMessage("message", "http://contoso.com");

It shows me an error when loading the page: iFrame.postMessage is not a function. When I execute the postMessage in console, I get an undefined

What am I doing wrong ?

Upvotes: 11

Views: 30447

Answers (3)

Djave
Djave

Reputation: 9349

I wasn't able to get this working using a querySelector approach.

What worked for me was the following. I'll refer to the two webpages as the parent that has an iframe on it and the src as the page inside the iframe.

On the src page, I post a message, with the parent url as the origin:

// src
window.parent.postMessage({
  type: "connect",
  url: window.location.href
}, "http://iframeparent.dev", );

Then in the parent page, I listen for this. It will have a property called source which is the iframe in question. This property can be posted to.

// parent
window.addEventListener("message", (event) => {
  // this is the magic connection:
  event.source; 
}, false);

So you could do something like:

// parent
let sources = [];

window.addEventListener("message", (event) => {
  sources.push(event.source);
}, false);

function something() {
  sources.forEach(source => {
    source.postMessage({some: "data"}, "http://iframesrc.dev")
  })
}

Upvotes: 10

Mathi kumar
Mathi kumar

Reputation: 403

Below code also works.

$('#id')[0].contentWindow.postMessage("hello world",targetOrigin);

There is a difference between jQuery selector and document.getElementById.

Document.getElementByID returns HTML DOM object.
jQuery selector returns jQuery object.

For more information please find below link. document.getElementById vs jQuery $()

Upvotes: 2

eknimation
eknimation

Reputation: 139

try this

var iFrame = document.getElementById('Frame');
iFrame.contentWindow.postMessage("message", "http://contoso.com");

I had this problem too. I found solution from this website https://www.viget.com/articles/using-javascript-postmessage-to-talk-to-iframes

Upvotes: 13

Related Questions