怜惜月110 2015-01-09 06:27 采纳率: 100%
浏览 2779
已采纳

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);
 } 
  • 写回答

4条回答 默认 最新

  • Go 旅城通票 2015-01-09 07:23
    关注

    你哪时注调用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秒发送信息
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波