如何查看iFrame向父窗口发送的消息?

时间:2018-02-11 12:13:27

标签: javascript iframe addeventlistener postmessage

我的页面上有一个iFrame,并且附加了一个事件监听器,但事件监听器没有被触发。如何查看iFrame发送到父窗口的消息(如果有)?

我的javascript:

<script>
    var game_id = "{{game_id}}";
    var gurl = "{{game_url}}"

    window.onload=function windowLoaded(){ // wait for the page to load
        var iframe = document.createElement('iframe');
        iframe.setAttribute("id", "game_frameid");
        iframe.setAttribute("name", "game_iframe");
        iframe.setAttribute("src", gurl);
        iframe.textContent += "Your browser doesn't support iframes";
        console.log("created iframe object")

        function receiveMessage(event){ // A fuction for handling messages to and from the iframe

            console.log("THIS event listener triggered");

        }

        document.getElementById("iframe_div").appendChild(iframe);
        document.getElementById("game_frameid").addEventListener("message", receiveMessage, false);
    }

iFrame代码:

  var message =  {
  messageType: "SETTING",
  options: {
    "width": 700, //Integer
    "height": 300 //Integer
    }
};
window.parent.postMessage(message, "*");

1 个答案:

答案 0 :(得分:0)

就像Xianshenglu说的那样,问题是我在监听窗口中iframe元素的事件,但是iframe正在向其父窗口发送消息。所以听众应该指向窗口iframe不在iframe本身。