Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't invoke a function in the child iframe by parent via postMessage() - cross origin

Tags:

I cannot get this CORS workaround to work in Chrome 52.0. My iframe and parent page are on different subdomains.

My iframe's event listener:

window.onload = function () {
    window.addEventListener("message", function(event) {
       //doesn't log it
       console.log('message');
       if(event.data === "invokeChildFunction()") {
           childFunction();
       }
    });
    function childFunction() {
        alert('Parent frame just invoked my function')
    }
}

The parent frame:

var iframeWindow = $('iframe').contentWindow;
var invokeChildFunction = function () {
  iframeWindow.postMessage("invokeChildFunction()", "https://mansion-assessment-sdimoff.c9users.io/CORS/index.html");
}

invokeChildFunction() doesn't log anything at the iframe's page

like image 214
Svetan Dimoff Avatar asked Aug 15 '16 01:08

Svetan Dimoff


People also ask

What is window postMessage () used for?

postMessage() The window. postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.

Does postMessage work cross domain?

PostMessage() is a global method that safely enables cross-origin communication. It's a lot like Ajax but with cross-domain capability. We'll give it a whirl by setting up two-way communication between a web page and an iframe whose content resides on another server.

How do I send a message to a child iframe?

Sending some data from the child iframe to the parent window is also pretty simple. Whenever you embed an iframe, the iframe will have a reference to the parent window. You just need to use the PostMessage API to send data via the window. parent reference of the parent window.


1 Answers

You should try using

In parent frame:

var iframe = $('iframe')[0];
iframe.contentWindow.postMessage('invokeChildFunction', iframe.contentWindow.location);

In child/iframe:

window.addEventListener('message', function (event) {
  if (event.data === 'invokeChildFunction') {
    // do whatever you want to
  }
})

What you did wrong was selecting elements with tag-name, on selecting elements with tag name you get an array of elements so you need to reference them as array.

Also use some validation to validate the source of events.

like image 99
Avi Avatar answered Sep 22 '22 16:09

Avi