美文网首页
iframe postMessage实现不同源通信

iframe postMessage实现不同源通信

作者: wojiaho | 来源:发表于2019-06-06 17:14 被阅读0次

需求说明

B页面需要拿到A页面的信息,这两个页面在不同的域名下,使用localStorage不能跨域,所以采用iframe的postMessage实现不同源通信

// A页面

export default class Hot extends React.Component {
  handerClick() {
    window.frames[0].postMessage('主页面消息', '*');
  }
  render() {
    return (
      <div>
        <iframe src="http://localhost:8080/#/login" id="child" />
        <button onClick={() => { this.handerClick(); }} >click</button>
      </div>
    );
  }
}

// B页面

window.addEventListener('message', function (e) {
      console.log(e.data)  //e.data为传递过来的数据
      console.log(e.origin)  //e.origin为调用 postMessage 时消息发送方窗口的 origin(域名、协议和端口)
      console.log(e.source)  //e.source为对发送消息的窗口对象的引用,可以使用此来在具有不同origin的两个窗口之间建立双向通信
    })

可以看到打印出来的结果

注意:

  1. 一定是页面加载完成后在发送消息,否则会因为 iframe 未加载完成报错。
  2. 在react中即使是写在componentDidMount中也拿不到data

参考文献:

  1. https://blog.csdn.net/tang_yi_/article/details/79401280

相关文章

网友评论

      本文标题:iframe postMessage实现不同源通信

      本文链接:https://www.haomeiwen.com/subject/pwpuxctx.html