iframe内联框中页面与父组件之间的几种通信方式

340 阅读1分钟

1. 消息发送与接收(跨源通信)

发送消息:
postMessage(message, targetOrigin,[transfer])
 参数: message:要发送到其他 window的数据
       targetOrigin:发送消息窗口的源(协议+主机+端口号),指定哪些窗口能接收到消息
       transfer:可选(默认false)
 接收消息:
 window.addEventListener("message", function (e) {
      console.log(e)
      console.log(e.data)
            // data:传递来的数据对象
            // source:发送消息的窗口对象
            // origin:发送消息窗口的源(协议+主机+端口号) 
    })

注意:始终使用origin和source属性验证发件人的身份

父向子通信:

父页面发送消息:
window.onload = function(){
    document.getElementById("Iframe").contentWindow.postMessage({title:'自定义标题'}, origin);
}
子页面接收:
window.addEventListener("message", function (e) {
    console.log(e)
    console.log(e.data)
},false)

子向父通信:

iframe页面调用:
window.parent.postMessage(data,origin);
父页面接收:
window.addEventListener("message", function (e) { },false)

2. 子父方法的调用(与vue子父组件信息互通类似)

子页面向父页面发送消息:

 父页面定义方法:
window.getChildVal = function(data){
    console.log(data)
}
子页面调用方法:
window.parent.getChildVal({title:'自定义标题'})

父页面向iframe子页面发送消息:

父页面定义方法:
window.sendChildVal = function(){
    var title="自定义标题"
    return title
}
子页面调用方法:
var getVal = window.parent.sendChildVal()
console.log(getVal)

3.params参数传递(父到子)

直接通过iframe的url?param=abc 方式, 把值传到子页面.