不同域iframe 与父页面消息通信
- 💡访问 iframe 页面中的方法
- 💡跨文本消息
- 监听消息
- 发送消息
var iframe = document.getElementById("myIframe");
var iframeWindow = iframe.contentWindow;
💡访问 iframe 页面中的方法
iframeWindow.methodName();
其中,methodName 为 iframe 页面中定义的方法名。需要注意的是,父页面和 iframe 页面必须同源(即协议、域名和端口号相同)才能访问彼此的方法
。如果两个页面不同源,则会出现跨域问题,无法相互访问。
💡跨文本消息
跨文档消息(Cross-document Messaging):使用postMessage API,在父页面和iframe之间进行消息通信。这样可以安全地在不同域之间传递数据,但需要在父页面和iframe中编写消息监听和处理的逻辑。
监听消息
💡在父页面中添加消息监听器,监听来自iframe的消息:
window.addEventListener("message", function(event) { // 判断消息来源是否为iframe if (event.source !== iframe.contentWindow) { return; } // 处理接收到的消息 console.log(event.data);
}, false);
💡在iframe页面中添加消息监听器,监听来自父页面的消息:
window.addEventListener("message", function(event) { // 判断消息来源是否为父页面 if (event.source !== parent.window) { return; } // 处理接收到的消息 console.log(event.data);
}, false);
发送消息
💡在父页面中向iframe发送消息
iframe.contentWindow.postMessage("Hello, iframe!", "https://example.com");
💡在iframe页面中向父页面发送消息
parent.window.postMessage("Hello, parent!", "https://example.com");
其中,postMessage方法的第一个参数为要发送的消息,第二个参数为接收消息的域(目标页面的window.location.href
),用于验证消息来源的安全性。需要注意的是,在使用postMessage进行消息通信时,需要确保父页面和iframe的通信协议和消息格式的定义一致,以避免出现通信失败或数据解析错误等问题。