无法通过父级通过 postMessage() 调用子 iframe 中的函数 - 跨源

Sve*_*off 5 javascript iframe postmessage cors

我无法在 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')
    }
}
Run Code Online (Sandbox Code Playgroud)

父框架:

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

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

Avi*_*Avi 4

你应该尝试使用

在父框架中:

var iframe = $('iframe')[0];
iframe.contentWindow.postMessage('invokeChildFunction', iframe.contentWindow.location);
Run Code Online (Sandbox Code Playgroud)

在子/iframe 中:

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

你做错的是选择带有标签名称的元素,在选择带有标签名称的元素时,你会得到一个元素数组,因此你需要将它们作为数组引用。

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