在JavaScript中,与子对话框(通常是通过window.open
打开的新窗口或通过<iframe>
嵌入的页面)进行通信可以通过多种方式实现。以下是一些基础概念和方法:
<iframe>
才能无障碍地进行通信。window.postMessage
方法:postMessage
可以避免直接访问其他窗口的对象,从而减少安全风险。window.frames
或window.opener
访问对方窗口的对象。window.postMessage
方法。父窗口代码:
// 打开子窗口
const childWindow = window.open('child.html', 'ChildWindow');
// 发送消息到子窗口
childWindow.document.getElementById('message').innerText = 'Hello from parent!';
// 接收子窗口的消息
window.addEventListener('message', (event) => {
if (event.source === childWindow) {
console.log('Message from child:', event.data);
}
});
子窗口代码(child.html):
<!DOCTYPE html>
<html>
<head>
<title>Child Window</title>
</head>
<body>
<div id="message"></div>
<script>
// 发送消息到父窗口
window.opener.postMessage('Hello from child!', '*');
// 接收父窗口的消息
window.addEventListener('message', (event) => {
if (event.source === window.opener) {
console.log('Message from parent:', event.data);
}
});
</script>
</body>
</html>
父窗口代码:
// 打开跨域子窗口
const childWindow = window.open('https://example.com/child.html', 'ChildWindow');
// 发送消息到子窗口
childWindow.postMessage('Hello from parent!', 'https://example.com');
// 接收子窗口的消息
window.addEventListener('message', (event) => {
if (event.origin === 'https://example.com') {
console.log('Message from child:', event.data);
}
});
子窗口代码(https://example.com/child.html):
<!DOCTYPE html>
<html>
<head>
<title>Child Window</title>
</head>
<body>
<script>
// 发送消息到父窗口
window.opener.postMessage('Hello from child!', 'https://parent-origin.com');
// 接收父窗口的消息
window.addEventListener('message', (event) => {
if (event.origin === 'https://parent-origin.com') {
console.log('Message from parent:', event.data);
}
});
</script>
</body>
</html>
event.origin
或event.source
的检查正确。event.origin
以防止恶意网站发送消息。postMessage
中使用通配符'*'
,而是指定具体的源。通过以上方法和注意事项,可以实现JavaScript与子对话框之间的安全、有效的通信。
云+社区技术沙龙[第15期]
云+社区技术沙龙[第23期]
企业创新在线学堂
云+社区技术沙龙[第6期]
云+社区沙龙online第6期[开源之道]
新知·音视频技术公开课