2016-11-07 184 views
0

我敢肯定这只是我的语法问题,但我试图发送一个变量到iframe(用于colorbox)。目前我接受任何两端的域名(只是为了让它工作)。下面是发送页面的JS:使用postMessage()没有收到

$(document).ready(function() { 
if(window.location.hash) { 
    var urlimage = window.location.hash.substring(1); 
    targetiframe = document.getElementById('wbgallery').contentWindow; 
    targetiframe.postMessage(urlimage, "*"); 
    console.log(urlimage); 
} 
}); 

这里是接收页:

$(document).ready(function() {  
window.addEventListener('message',receiveMessage); 
console.log(event); 
function receiveMessage(event) { 
    if (origin !== "*") 
    return; 
    inbound = event.data; 
    console.log(inbound); 
} 
}); 

我看到控制台日志urlimage,可以看到入站事件,但没有。我使用Mozilla's explanation来尝试和全​​力以赴。

+1

'receiveMessage'是使用从未设置变量'origin'。所以它返回。 – Barmar

+0

您还在'event'参数的函数外部有'console.log(event)'。那应该做什么? – Barmar

+0

我想'origin'应该是'event.origin',但你为什么还要打扰呢?它永远不可能是'*',它总是一个URL。 – Barmar

回答

0

您正在加载iframe中的页面之前发送消息,因此message侦听器尚未建立。

您可以让iframe在准备就绪时向其发送消息,然后在此之后发送消息。

父代码:

$(document).ready(function() { 
    if (window.location.hash) { 
    var urlimage = window.location.hash.substring(1); 
    var targetiframe = document.getElementById('wbgallery').contentWindow; 
    $(window).on("message", function(e) { 
     targetiframe.postMessage(urlimage, "*"); 
     console.log(urlimage); 
    }); 
    } 
}); 

的iframe代码:

$(document).ready(function() { 
    $(window).on('message', function(event) { 
    inbound = event.data; 
    console.log(inbound); 
    }); 
    window.parent.postMessage("ready", "*"); 
}); 
+0

嗨,只是快速的问题。我得到了“Uncaught SyntaxError:missing)在参数列表后出现错误,并指出它在'receiveMessage(event)'的某个地方......我不明白,因为根据jQuery的.on()文档,它看起来都很好。有任何想法吗? – Daniel

+0

对不起,这是一个编辑错误,它应该是'功能(事件)' – Barmar

+0

谢谢,现在工作。但是,你知道为什么event.data会返回'undefined'吗?该发送页面上的变量是正确的,但似乎没有正确传递? – Daniel