iframe 跨域双向通信

1 父页面向 iframe 传参

1.1 父页面发消息

// `iframeEl` 是 iframe 所对应的 HTML 元素
iframeEl.contentWindow.postMessage('message body', '*'); 

1.2 iframe 监听并校验消息

window.addEventListener('message', function(event) { 

      // IMPORTANT: Check the origin of the data! 
      console.log(event.origin);
      // 收到消息后一定要校验,防止被恶意利用
      if (~event.origin.indexOf('http://parentdomain.com')) { 
          // The data has been sent from your site 
  
          // The data sent with postMessage is stored in event.data 
          console.log(event.data); 
      } else { 
          // The data hasn't been sent from your site! 
          // Be careful! Do not use it. 
          console.log(event.data)
          return; 
      } 
  });

2 iframe 向父页面传参

2.1 iframe 发送消息

// 注意发消息时多了个 `parent`
window.parent.postMessage(params, '*');

2.2 父页面监听并校验消息

window.addEventListener('message', function(event) { 

      // IMPORTANT: Check the origin of the data! 
      console.log(event.origin);
      // 收到消息后一定要校验,防止被恶意利用
      if (~event.origin.indexOf('http://iframedomain.com')) { 
          // The data has been sent from your site 
  
          // The data sent with postMessage is stored in event.data 
          console.log(event.data); 
      } else { 
          // The data hasn't been sent from your site! 
          // Be careful! Do not use it. 
          console.log(event.data)
          return; 
      } 
  });

参考