无法通过postMessage() - cross origin来调用父级iframe中的函数

时间:2016-08-15 01:11:31

标签: javascript iframe cors postmessage

我无法在Chrome 52.0中使用此CORS解决方法。我的iframe和父页面位于不同的子域名中。

我的iframe的事件监听器:

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')
    }
}

父框架:

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

invokeChildFunction()不会在iframe的页面上记录任何内容

1 个答案:

答案 0 :(得分:1)

你应该尝试使用

在父框架中:

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

在child / iframe中:

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

你做错了是选择带有tag-name的元素,在选择带有标签名称的元素时你得到一个元素数组,所以你需要将它们作为数组引用。

还可以使用一些验证来验证事件来源。