我正在向 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>
最佳答案
我无法理解这个“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
关于javascript - 动态添加属性的 postMessage 未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54106245/