iframe 特点
窗口不会收到自己发送的消息
iframe 发送 消息时候,如果通信双方 A,B 发送的都是 hello,是不是 A 不能收到自己的 hello,只能收到 B 的 hello
在使用 iframe 进行消息传递时,通信双方(如 A 和 B)可以通过 postMessage 方法来发送消息。每个窗口(或 iframe)都可以发送和接收消息,但通常情况下,窗口不会收到自己发送的消息。也就是说,如果窗口 A 发送了消息 "hello",它不会收到这条消息,但窗口 B 会收到。同样地,如果窗口 B 也发送了消息 "hello",窗口 A 会收到这条消息,但窗口 B 自己不会收到。
示例说明
假设我们有两个窗口:主窗口 A 和嵌入的 iframe B。以下是一个简单的示例,展示如何在这两个窗口之间发送和接收消息。
主窗口 A 的代码
<!DOCTYPE html>
<html>
<head>
<title>Main Window</title>
</head>
<body>
<iframe id="myIframe" src="iframe.html"></iframe>
<script>
const iframe = document.getElementById('myIframe').contentWindow;
window.addEventListener('message', (event) => {
if (event.origin !== window.location.origin) {
return; // 确保消息来自可信任的源
}
console.log('Main window received:', event.data);
});
// 发送消息到 iframe
iframe.postMessage('hello from main window', window.location.origin);
</script>
</body>
</html>
iframe B 的代码(iframe.html)
<!DOCTYPE html>
<html>
<head>
<title>Iframe Window</title>
</head>
<body>
<script>
window.addEventListener('message', (event) => {
if (event.origin !== window.location.origin) {
return; // 确保消息来自可信任的源
}
console.log('Iframe received:', event.data);
// 发送消息回主窗口
event.source.postMessage('hello from iframe', event.origin);
});
// 发送消 息到主窗口
window.parent.postMessage('hello from iframe', window.location.origin);
</script>
</body>
</html>
解释
-
主窗口 A:
- 创建一个
iframe并引用iframe.html。 - 监听
message事件以接收来自iframe的消息。 - 使用
postMessage方法发送消息到iframe。
- 创建一个
-
iframeB:- 监听
message事件以接收来自主窗口的消息。 - 使用
postMessage方法发送消息回主窗口。
- 监听
通信过程
- 主窗口 A 发送消息 "hello from main window" 到
iframeB。 iframeB 接收到消息并打印 "Iframe received: hello from main window"。iframeB 发送消息 "hello from iframe" 回主窗口 A。- 主窗口 A 接收到消息并打印 "Main window received: hello from iframe"。
在这个过程中,每个窗口都不会接收到自己发送的消息,而是接收对方发送的消息。
总结
是的,在 iframe 通信中,如果 A 和 B 都发送 "hello",A 不会收到自己发送的 "hello",而只能收到 B 发送的 "hello"。同样地,B 也不会收到自己发送的 "hello",而只能收到 A 发送的 "hello"。这种行为确保了消息传递的方向性和有效性。