postMessage发送数据
<postMessage往不同窗口里面发送数据>2022年11月14日一个页面通过iframe引入另外一个页面,页面之间如何通讯?两个页面就存在两个window,存在跨域。父子页面可以通过window.postMessage进行通讯。
1、子页面使用window.postMessage通讯;
2、父页面使用window.addEventListener("message", receiveMessage, false);实时接收子页面的数据。
<父窗口>
<iframe src="test2.html"></iframe>
<script>
function receiveMessage(e) {
alert(e.data);
}
window.addEventListener("message", receiveMessage, false);
</script>
<子窗口test2.html>
<input type="text" value="send" id="input" />
<input type="button" value="send" id="button" />
<script>
document.getElementById('button').onclick = function () {
top.postMessage(document.getElementById('input').value, '*');
};
</script>
页:
[1]