原因:
确保目标 iframe 完全加载 contentWindow.postMessage 只能在目标 iframe 完全加载之后正常工作。如果目标 iframe 尚未加载完成,消息可能无法到达。确保 iframe 完全加载并准备好接收消息。
解决方案:
const iframe = document.getElementById('myIframe');
// 等待 iframe 加载完成
iframe.addEventListener('load', () => {
const iframeWindow = iframe.contentWindow;
iframeWindow.postMessage('Hello from parent', '*');
});