The Channel Messaging API allows two separate scripts running in different Browsing Contexts attached to the same document (e.g., two <iframe> elements, the main document and a single <iframe>, or two documents via a SharedWorker) to communicate directly, passing messages between each other through two-way channels (or pipes) with a port at each end. mdn
Note: For more information and ideas, the Ports as the basis of an Object-Capability Model on the Web section of the spec is a useful read. page
To get you started, we have published a couple of demos on GitHub. First, check our channel messaging basic demo (run it live too ), which shows a really simple single message transfer between a page and an embedded <iframe>. github
# Assets
pages/channel-messaging-basic
We copy the script code from index.html into a code snippet to evaluate it within the 2 JS Snippet Template frames below (based on importjs.html copied to page1.html and page2.html).
const channel = new MessageChannel(); const outputPage1 = document.getElementById('outputPage1'); const outputPage2 = document.getElementById('outputPage2');
We get "can't access property "addEventListener", iframe is null".
See "Cannot read property 'addEventListener' of null" stackoverflow
The JS Snippet Template gives us a div with id output. So we change the code for the const output above to use getElementById. Now we can use the debugger to check if output is within the scope of the JS Snippet Template frame. We see the text "waiting" (from the pre element with the id show)
function onMessage(e) { console.log("(onMessage) reached."); outputPage1.innerHTML = e.data; outputPage2.innerHTML = e.data; }
// Listen for messages on port1 channel.port1.onmessage = onMessage;
// Transfer port2 to the outputPage2 outputPage2.postMessage("Hello from the main page!", "*", [ channel.port2, ]);
JS Snippet Template – page 1
http://localhost:3000/assets/pages/channel-messaging-basic/page1.html
JS Snippet Template – page 2
http://localhost:3000/assets/pages/channel-messaging-basic/page2.html
The text "iFrame body" comes for a p with class output within page2.html.
We refactor the code above to use page2 instead of iframe and change the code of page2.html to be able to use getElementById "page2Output".
# Event listener