【问题标题】:Can't invoke a function in the child iframe by parent via postMessage() - cross origin父级无法通过 postMessage() 调用子 iframe 中的函数 - 跨域
【发布时间】:2016-08-15 01:11:30
【问题描述】:

我无法在 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 页面上记录任何内容

【问题讨论】:

  • window 分配给iframe var window = $('iframe').contentWindow; 的目的是什么?
  • @guest271314 我正在尝试引用 iframe 窗口。我应该怎么做呢?
  • 会尝试使用window 以外的标识符以避免混淆。 window 的来源不同吗?
  • 好的,我把它改成iframe。但这并不能解决问题。当我从孩子那里发送时它有效。是的,这应该可以跨域工作

标签: javascript iframe cors postmessage


【解决方案1】:

你应该尝试使用

在父框架中:

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

在子/iframe 中:

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

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

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

【讨论】:

  • 如果如 OP 所述,我的 iframe 和父页面位于不同的子域上,这是否有效。
  • 是的 window.postMessage 可以用来在不同子域的页面之间进行通信。您可以check this 进一步澄清。
猜你喜欢
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-23
  • 2020-05-04
  • 2014-07-01
  • 2012-02-08
相关资源
最近更新 更多