簡體   English   中英

PostMessage 到同一域的嵌套 iframe - JavaScript

[英]PostMessage to nested iframe of the same domain - JavaScript

是否可以將 postMessage 發送到嵌套的 iframe?

我有父頁面 [ 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>

在父頁面中,它將調用另一個瀏覽器到 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>
  

如果它只是一個 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>

postMessage 是否僅適用於單個幀?

Window 消息不會“冒泡”; 您可以:

  1. 在孫子頁面中,在window.parent甚至window.top上收聽一些內容,並處理最頂層 window 上的所有消息發布; 或者
  2. 在最上面的頁面中,向下嵌套兩次: document.getElementById('tableauFrame').contentDocument.querySelector('iframe').contentWindow.postMessage("success", "*")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM