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);
});