Issue communication with postMessage from parent to child iFrame

16,366

Solution 1

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

Solution 2

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 $()

Solution 3

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")
  })
}
Share:
16,366
Hubert Solecki
Author by

Hubert Solecki

Updated on June 13, 2022

Comments

  • Hubert Solecki
    Hubert Solecki almost 2 years

    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 ?

  • temo
    temo over 5 years
    Error: Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin. It works from child element to parent but not the way around.
  • Djave
    Djave over 2 years
    @temo I was able to get it working cross domain, see my answer below.