浏览器跨域消息传递

Administrator 0 阅读 博客

父页面给子页面传值

const iframe = document.getElementId('iframe')//iframe容器
iframe.contentWindow.postMessage({msg: '来自父页面的消息'}, "*");

子页面接收消息

  window.onmessage = function(event){
  console.log(event.data.msg) // 来自父页面的消息
}

子页面给父页面传递消息

window.parent.postMessage({msg: '来自子页面值'}, "*");

父页面接收消息

window.onmessage = function(event){
    console.log(event.data.msg) // 来自子页面值
}