将JavaScript发送到使用其他端口的iFrame?

时间:2015-11-27 20:08:19

标签: javascript iframe

我一直有一些问题将JavaScript发送到使用不同端口的iFrame,并且在网上搜索后,似乎“不同端口”部分导致了问题。

以下是将JavaScript发送到iFrame的代码:

<script>
    var network = document.getElementById("1").contentWindow.kiwi.components.Network();

    $(".irc-channel-selector").click(function(event){
        network.join('#' + $(this).attr('data-irc-channel'));
    });
</script>

iFrame不使用端口80,这似乎是问题所在:

<iframe id="1" src="http://www.example.com:7888">

据我所知,我可以使用一个名为postMessage的东西来做我需要的东西,但是在线阅读它我不知道应该如何使用它,它似乎相当复杂而我只习惯基本JavaScript,例如我上面写的代码。

有人可以举例说明我如何使用这个postMessage来模仿上面的行为吗?阅读在线文档我不明白如何在我的场景中使用它! :(

1 个答案:

答案 0 :(得分:0)

使用postMessage实现此目标并不是非常复杂。首先,在iframe中,您必须要有一条消息:

var network = kiwi.components.Network();

function receive(event) {
    // it is important to check the origin. Here I'm assuming that the parent window has that origin (same address, default port).
    // if you don't check the origin any other site could include your iframe and send messages to it
    if (event.origin === "http://www.example.com") { 
        var message = event.data;
        // Assuming you might want different message types in the future. Otherwise message could be just the channel itself.
        if (message.type === "JOIN") { 
            network.join(message.channel);
        }
    }
}

window.addEventListener("message", receive, false);

现在您的iframe页面正在等待消息使其加入频道。父页面可以使用以下内容发送该消息:

$(".irc-channel-selector").click(function(event){
    var message = {
        type: "JOIN",
        channel: '#' + $(this).attr('data-irc-channel')
    };

    // Notice that again we're using the specific origin you used in your iframe
    document.getElementById("1").contentWindow.postMessage(message, "http://www.example.com:7888");
});

这里是一个更简单的小提琴,其中一条消息被发送到同一个窗口,因为我必须在某个地方托管一个页面以在jsfiddle中有一个iframe:https://jsfiddle.net/3h1Lw0j4/1/ - 无论如何它& #39;有助于了解event.origin的行为方式。

相关问题