iframe之父子页面相互传参

思路:

父传子:

发送方:

iframe.contentWindow.postMessage('要传的参数', '*')

接收方:

window.addEventListener("message", function(e){...}, false) // e是个对象,里面包含了传过来的参数

子传父:

发送方:

parent关键字表示父窗口,如果一个窗口没有父窗口,则它的 parent 属性为自身的引用.

parent.postMessage('要传的参数', '*')

接收方:

window.addEventListener("message", function(e){...}, false) // e是个对象,里面包含了传过来的参数

父页面

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .father {
      width: 500px;
      height: 500px;
      margin: 0 auto;
      background-color: brown;
      border: 2px solid black;
    }
    iframe {
      width: 200px;
      height: 200px;
      margin: 0 auto;
      display: block;
      background-color: bisque;
      border: 2px solid black;
    }
    #btn {
      display: block;
      margin: 0 auto;
    }
  </style>
</head>
<body>
  <div class="father">
    <p></p>
    <iframe src="./iframe-子页面.html" frameborder="0" id="iframe"></iframe>
    <button id="btn">父传子</button>
    <script>
      const iframe = document.getElementById('iframe')
      const btn = document.getElementById('btn')
      const p = document.querySelector('p')
      const receiveMsg = function(e) {
        const { data } = e
        if (data.id === 'son') {
          p.innerText = data.msg
          p.style.color = 'white'
        }
      }
      btn.onclick = function (e) {
          iframe.contentWindow.postMessage({
            id: 'father',
            msg: '要传给子页面的值'
          }, '*')
        }
      window.addEventListener("message", receiveMsg, false)
      window.a = '父页面'
    </script>
  </div>
</body>
</html>

子页面

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
  </style>
</head>
<body>
  <div class="son">
    <b></b>
    <button onclick="sendMsg()">子传父</button>
  </div>
  <script>
    //监听message事件
    const b = document.querySelector('b')
    const receiveMsg = function (e) {
      const { data } = e
      if (data.id === 'father') {
        b.innerText = data.msg
      }
    }
    window.addEventListener("message", receiveMsg, false)
    const sendMsg = function() {
      parent.postMessage({
        id: 'son',
        msg: '传给父页面的值'
      }, '*')
    }
    console.log(window.parent.a) // 父页面
  </script>
</body>
</html>

效果图:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值