2
請讓我有一個小窗體,我打開窗口像下面的窗口。在新窗口中打開一個iframe的postMessage
<html>
<head>
</head>
<body>
<div id="popUpDiv" style="display:none;"></div>
<script type="text/javascript">
var popUpWindow;
function popup(n) {
popUpWindow = window.open("",n, "height=500,width=500");
}
function foo(obj){
test1 = "http://localhost:3001";
popUpWindow.document.write('<iframe height="450" id="receiver" allowTransparency="true" frameborder="0" scrolling="yes" style="width:100%;" src="'+test1+'" type= "text/javascript"></iframe>');
}
</script>
<a href="#" onclick="popup('popUpDiv');foo(this);">OnSale</a>
</body>
</html>
上面是父窗體並且正在服務器localhost:3000上運行。我打開了一個新的窗口,上面有一個iframe。我打算從popup或子窗口中postMessage並在父窗口中接收它。然後我修改了我的代碼,在下面添加onload。
window.onload = function() {.
var messageEle = document.getElementById('message');
console.log('its receiving message');
function receiveMessage(e) {
alert('received');
console.log('the origin is ', e.origin);
if (e.origin !== "http://localhost:3001"){
return;
}
messageEle.innerHTML = "Message Received: " + e.data;
}
window.addEventListener('message', receiveMessage);
}
現在我的完整父頁面如下所示。
<html>
<head>
</head>
<body>
<div id="popUpDiv" style="display:none;"></div>
<script type="text/javascript">
var popUpWindow;
function popup(n) {
popUpWindow = window.open("",n, "height=500,width=500");
}
function foo(obj){
test1 = "http://localhost:3001";
popUpWindow.document.write('<iframe height="450" id="receiver" allowTransparency="true" frameborder="0" scrolling="yes" style="width:100%;" src="'+test1+'" type= "text/javascript"></iframe>');
}
window.onload = function() {
var messageEle = document.getElementById('message');
console.log('its receiving message');
function receiveMessage(e) {
alert('received');
console.log('the origin is ', e.origin);
if (e.origin !== "http://localhost:3001"){
return;
}
messageEle.innerHTML = "Message Received: " + e.data;
}
window.addEventListener('message', receiveMessage);
}
</script>
<a href="#" onclick="popup('popUpDiv');foo(this);">OnSale</a>
<div id="message"></div>
</body>
</html>
當我點擊父Onsale的鏈接,它打開了我的孩子從服務器3001。然而,孩子控制檯上運行
parent.postMessage('Hello', 'http://localhost:3000');
不火的的receiveMessage事件家長。我確認我的活動已附加。我嘗試了一切可能,但沒有任何改變請問我做錯了什麼?任何幫助,將不勝感激
謝謝,它適用於類似情況下的我。在新窗口中運行時,需要將** postMessage **發送到** opener **而不是** parent **。在我的情況下,我需要使它適用於這兩種情況,所以我檢查開放者的存在:「開罐器? opener.postMessage('Hello','https://target.url'):parent.postMessage('Hello','https://target.url')' – Rafa