[英]PostMessage to nested iframe of the same domain - JavaScript
Will it be possible to send postMessage to a nested iframe?是否可以将 postMessage 发送到嵌套的 iframe?
I have parent page [ http://localhost:8765/home.html ], I have declared postMessage function in the parent page as below snippet我有父页面 [ http://localhost:8765/home.html ],我已经在父页面中声明了 postMessage function 如下片段
// home.html [http://localhost:8765/homr.html]
<html>
<script>
function test1(){
document.getElementById('tableauFrame').contentWindow.postMessage("success", "*")
}
</script>
<body>
child ui <br>
<iframe width='2000px' height='2000px' src='http://localhost:8766/child.html' id='tableauFrame' onload=test1()></iframe>
</body>
</html>
Inside parent page, it will call another browser to an iframe, in child browser it has another iframe which is calling page2.在父页面中,它将调用另一个浏览器到 iframe,在子浏览器中它有另一个正在调用 page2 的 iframe。
//child.html [ http://localhost:8766/child.html ]
<html>
<body>
<p>Child page</p>
<iframe src='http://localhost:8766/page2.html' id='secondary'></iframe>
</body>
</html>
if it was just a single iframe [ parent (home.html) to child(child.html)], it will work and receive the message, but when I tried a nested iframe parent(home.html) to grandchild[page2.html] element, it is not receiving the postMessage.如果它只是一个 iframe [父(home.html)到子(child.html)],它将工作并接收消息,但是当我尝试嵌套 iframe 父(home.html)到孙 [page2.html ] 元素,它没有接收到 postMessage。
// grandchild [ http://localhost:8766/page2.html ]
<html>
<script>
window.addEventListener('message',function(message){
if (event.origin === "http://localhost:8765") {
console.log("displaying message from parent page : " + message.origin)
}
})
</script>
<body>
<p>this is getting from 3rd page</p>
</body>
</html>
Does postMessage only work on a single frame? postMessage 是否仅适用于单个帧?
Window messages don't "bubble down"; Window 消息不会“冒泡”; you can either:
您可以:
window.parent
or even window.top
, and handle all message posting on the topmost window;window.parent
甚至window.top
上收听一些内容,并处理最顶层 window 上的所有消息发布; ordocument.getElementById('tableauFrame').contentDocument.querySelector('iframe').contentWindow.postMessage("success", "*")
document.getElementById('tableauFrame').contentDocument.querySelector('iframe').contentWindow.postMessage("success", "*")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.