具有动态添加属性的postMessage未定义错误

时间:2019-01-09 08:52:08

标签: javascript iframe attributes cross-domain postmessage

我正在向iframe动态添加“ name = true ”属性。收到错误“无法读取未定义的属性'postMessage'”   但是使用相同的“ window.iframe.true”

在控制台上可以正常工作

已更新:“ win”返回未定义

<iframe src="crossdomain.com" id="iframe"></iframe>

<script>
    var win = window.iframe.nametrue;
    win.postMessage("statusPause", "othersite.com");
</script>

2 个答案:

答案 0 :(得分:2)

我无法理解此“ nametrue”。然而。这至少应该解决未定义的问题。

var win = document.getElementById('iframe');
win.contentWindow.postMessage("statusPause", "othersite.com");

正如您在此处看到的https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage postMessage需要一个有效的目标窗口。您的“ window.iframe.nametrue”没有任何针对性,即使如此。它可能不是预期的有效目标窗口。 我使用getElemenetById获得了iframe,并在获得的iframe上调用了“ contentWindow”,这将根据需要返回有效的targetWindow

答案 1 :(得分:0)

在将胜利分配给iframe之前,您需要分配属性name="nametrue"