Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Cross-Window Communication</title> <style> #childIframe, #childPopup { width: 100%; height: 200px; border: 1px solid black; margin-top: 20px; } </style> </head> <body> <h1>Cross-Window Communication Examples</h1> <!-- Button to Open Popup --> <button id="openPopup">Open Popup</button> <div id="parentPopupDisplay"></div> <!-- Iframe --> <iframe id="childIframe" srcdoc=" <!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <title>Child Iframe</title> </head> <body> <div id='childIframeDisplay'></div> <script> window.addEventListener('message', (event) => { if (event.origin !== window.location.origin) return; document.getElementById('childIframeDisplay').innerText = 'Message from parent: ' + event.data; event.source.postMessage('Hello, Parent Window!', event.origin); }); </script> </body> </html> "></iframe> <div id="iframeDisplay"></div> <!-- Scripts for Parent Window --> <script> // Handle Popup Communication document.getElementById('openPopup').addEventListener('click', () => { const popup = window.open('', 'popupWindow', 'width=600,height=400'); popup.document.write(` <!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <title>Popup Window</title> </head> <body> <div id='popupDisplay'></div> <script> window.addEventListener('message', (event) => { if (event.origin !== window.location.origin) return; document.getElementById('popupDisplay').innerText = 'Message from parent: ' + event.data; event.source.postMessage('Hello, Parent Window!', event.origin); }); <\/script> </body> </html> `); setTimeout(() => { popup.postMessage('Hello from parent!', '*'); }, 1000); }); // Handle Iframe Communication const iframe = document.getElementById('childIframe'); iframe.onload = () => { iframe.contentWindow.postMessage('Hello from parent window!', '*'); }; window.addEventListener('message', (event) => { if (event.origin !== window.location.origin) return; if (event.source === iframe.contentWindow) { document.getElementById('iframeDisplay').innerText = 'Message from iframe: ' + event.data; } else { document.getElementById('parentPopupDisplay').innerText = 'Message from popup: ' + event.data; } }); </script> </body> </html>