2015-11-27 23 views
-1

我一直有一些問題發送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來模仿上面的行爲的例子嗎?閱讀在線文檔我不明白如何在我的場景中使用它! :(

+0

你對iframe中的javascript/html有控制嗎?如果是這樣,'postMessage'可能是您最好的解決方案,相信我並不比您已經完成的複雜得多!查看https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage中的示例 - 如果您確實可以控制iframe中的代碼,我可以發佈一個可能的答案。 – Sergio

+0

@Sergio是的,我確實控制它,如果你能做到這一點,我會非常感激! – user5603796

回答

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"); 
}); 

這裏就是一個消息被髮送到同一個窗口一個更爲簡單的小提琴,因爲我不得不地方舉辦一個網頁有一個iframe中的jsfiddle:https://jsfiddle.net/3h1Lw0j4/1/ - 無論如何,看到h是有用的ow event.origin表現。

+0

謝謝,我一直在玩這個幾個小時!我一直收到'無法發送消息到http://www.example.com:7778。收件人在我的控制檯中有起源http:// www.example.com.:( – user5603796

+0

)iframe中是否有重定向?嘗試調用帶有在錯誤消息中指定的原點的postMessage:contentWindow.postMessage(message ,「http://www.example.com」);' – Sergio

相關問題