JS HTML5跨域跨窗口通信postMessage问题求帮助

 this.exportUnits = d;
                 var g = "status=no,resizable=no,scrollbars=yes,personalbar=no,directories=no,location=no,toolbar=no,menubar=no,width=760,height=530,left=60,top=80";

                 this.popupWindow = b.open(a.settings.multiPopupUrl, "", g);
                 if (this.exportUnits && this.exportUnits.length) {
                     var bs = JSON.stringify(this.exportUnits);
                     this.popupWindow.postMessage(bs, a.settings.multiPopupUrl)
                 }


上述代码是打开一个新窗口同时postMessage一段消息到弹出的新窗口,但是弹出的新窗口有时收到有时收不到,收到的几率很少,求大神帮助

下面是新窗口接收的代码

 function loadImg() {
     window.addEventListener("message", receiveMessage, false);
 }
 function receiveMessage(event) {
     alert(event.origin);
     alert(event.data);
     alert(event.source);
 } 

你哪时注调用loadImg()这个放在注册onmessage事件的?不会是在body的onload事件中吧。。这样注册事件太晚了,你是打开窗口后就直接发信息了,你打开的窗口可能都还没注册onmessage事件先

注册onmessage事件不要放到onload中,script直接放到head标签中进行注册

 <head>
 function receiveMessage(event) {
     alert(event.origin);
     alert(event.data);
     alert(event.source);
 } 
window.addEventListener("message", receiveMessage, false);
</head>

延时发送信息。这个延时时间不好确定,应为打开的页面依赖于网速,要是很慢,10多s才打开延时也无效了。。最好是发送信息的页面也注册onmessage事件,然后被打开的页面注册好事件后发送信息过来通知说我注册号事件了,你再发送信息过去。。这个逻辑你自己实现了,也不难~

  if (this.exportUnits && this.exportUnits.length) {
                var me=this;
                setTimeout(function(){
              var bs = JSON.stringify(me.exportUnits);
              me.popupWindow.postMessage(bs, a.settings.multiPopupUrl)
                },1000);//延时1秒发送信息
 }

页面一加载就注册事件。没注册上就没法收到消息
发送消息的时候,延时测试一下

已经解决了,谢谢各位大神

用的是 发送信息的页面也注册onmessage事件,然后被打开的页面注册好事件后发送信息过来通知说我注册号事件了,你再发送信息过去