iframe标签下的通信

  • iframe标签下的通信已关闭评论
  • 127 次浏览
  • A+
所属分类:Web前端
摘要

通常在页面中嵌套iframe的情况下还需要进行消息传递的通信需求。一般分为两种情况:

通常在页面中嵌套iframe的情况下还需要进行消息传递的通信需求。一般分为两种情况:

1.iframe里的链接与父页面链接是非跨域

        这种情况处理比较简单,直接在父级页面下就可以写脚本控制iframe里的元素,同时对iframe里的元素进行操作,例如绑定事件,当事件触发时发送消息给父级页面。

        具体实践脚本如下:

    try{      //绑定窗口消息事件,接收来iframe发送的消息     window.addEventListener('message', function(ev) {          if(ev.data.source == 'pt_event' && ev.data.message == 'iframeButton'){              _pt_sp_2.push('setCustomEvent',{eventName:'buy_product'});          }      }, false)      //为了避免iframe加载较慢,等2s后绑定元素事件,处理事件触发后获取相关信息并发送父级页面     setTimeout(function(){          var buttons = document.querySelectorAll('div[id^=product-component-');          if(buttons){              buttons.forEach(function(iframeButton){                          iframeButton.querySelector('iframe').contentDocument.body.                     querySelector('.shopify-buy__btn').                     addEventListener('click',function(){                         var msg={};                          msg['source'] = 'pt_event';                          msg['message'] = 'iframeButton';                        parent.postMessage(msg,'*');                      },false)              })          }      },2000)  }catch(e){      console.log('ptmsg:'+e)  }

2.iframe里的链接与父页面链接是跨域关系,这种情况需要在父页面与iframe里分别进行编写脚本进行接收消息与发送消息。

        父页面中监听消息:

try{      window.addEventListener('message', function(ev) {          if(ev.data.source == 'pt_event' && ev.data.message == 'iframeButton'){              _pt_sp_2.push('setCustomEvent',{eventName:'buy_product'});          }      }, false)  }catch(e){      console.log('ptmsg:'+e)  } 

        iframe中事件监听及发送消息:

try{      var btn_event = document.body.querySelector('.layout_image');      if(btn_event){          btn_event.addEventListener('click',function(){          var msg={};          msg['source'] = 'pt_event';          msg['message'] = 'iframeButton';          parent.postMessage(msg,'*');          },false)      }  }catch(e){      console.log('ptmsg:'+e)  }