You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1.4 KiB
HTML

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>Parent Window</title>
</head>
<body>
<div>我是父窗口</div>
<button id="openWindow">打开一个新的子窗口</button>
<button id="sendMsg">点击给子窗口发送信息</button>
<script>
// 存储子窗口实例
let childWindow;
document.getElementById('openWindow').onclick = function () {
// 打开新窗口, 第三个参数内容必须带否则不会以新的浏览器窗口打开而是以新的标签页tab打开
childWindow = window.open('https://child-domain.com', '_blank', 'width=800,height=600');
};
document.getElementById('sendMsg').onclick = function () {
childWindow.postMessage('给子窗口传跨域跨标签消息', 'https://child-domain.com');
};
// 监听来自子窗口的消息
window.addEventListener('message', (event) => {
// 验证消息来源
if (event.origin === 'https://child-domain.com') {
console.log('接受子窗口跨域跨标签消息:', event.data);
}
});
</script>
</body>
</html>