iframe父子页面传参数

1.子传父

子页面中

html页面添加一个按钮

  <button id="btn">子页面的按钮</button>

在js中使用 window.parent.postMessage(date,origin)方法进行跨源传递。
第一个参数代表的是数据,第二个参数代表地址,* 代表全部地址。

 <script>
            document.getElementById('btn').onclick = function () {
                window.parent.postMessage(
                    {
                        msg: { a: '回首掏,哟', b: '鬼刀一开看不见!'}
                    },
                    '*'
                );
            };
</script>

父页面中

在html中

<iframe src="./son.html" frameborder="0" name="myframe" id="myframe"></iframe>

在js中使用message方法接受数据

window.addEventListener('message', function (e) {
      console.log(e.data);
 });

在这里插入图片描述

2.父传子

父页面中

父页面html中添加一个按钮

       <h2>我是父级页面</h2>
       <button id="btn">父页面的按钮</button>
       <iframe src="./son.html" frameborder="0" name="sonIframe" id="sonIframe"></iframe>

通过contentWindow.postMessage(date,origin)来进行传递,参数与子串父一致。

		 document.getElementById('btn').onclick = function () {
                var myIframe = document.getElementById('sonIframe');
                myIframe.contentWindow.postMessage(
                    {
                        data: {
                            a: '走位,走位~',
                            b: '手里剑,难受~'
                        }
                    },
                    '*'
                );
            };

子页面中

子页面中同样使用message方法进行接受

       window.addEventListener('message', function (e) {
                console.log('子接受参数了', e.data);
        });

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hope°

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值