跨域数据利用iframe传输示例

点击入口栏,跳转本域空白页iframe铺满全屏加载目标页,选择数据后postMessage到父页面,父页面读取数据并回退到业务页,业务页读取已记录的地址并刷新数据。

主项目:

<iframe id='addressIframe' onLoad={initPostEvt} style={{'zIndex': 666, 'display': 'block', 'width': '100%', height: '100%', position: 'fixed'}} 
      src='https://local.test.tianchendajiankang.com:3002/#/newAddAdressList?from=b2c&originFrom=b2c&shopId=58&shopLat=23.097027&shopLng=113.2701'></iframe>

const evtCall = (e) => {
  if (e.origin === 'https://local.test.tianchendajiankang.com:3002') {
	  // 本地缓存或者redux
    window.sessionStorage.setItem('b2caddress', JSON.stringify(e.data))
    window.history.go(-1)
  }
}
const initPostEvt = () => {
  let receiver = document.getElementById('addressIframe').contentWindow;
  receiver.postMessage("Hello", "https://local.test.tianchendajiankang.com:3002");// 主动握手使子页面逻辑初始化
  // window.removeEventListener('message', evtCall)
  window.addEventListener('message', evtCall)
}

目标项目:

componentDidMount() {
    const this_ = this;
    window.addEventListener('message', function(e) {
        if (e.origin === 'https://local.test.tianchendajiankang.com:3010') {
            this_.frameSource = e.source;  // 初始化合法页面源
        }
    })
}
// 点击地址post数据
choseAddress(e, data) {
        let { from, doctorShop ,prescriptionId,channel,latitude,longitude, ejkToken,shopId,deliveryTypeStr} = this.query;
        if (from == 'b2c') {
            this.frameSource && this.frameSource.postMessage(data, 'https://local.test.tianchendajiankang.com:3010')
            return;
        }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值