We think of message channels as a Yoghurt-pot Telephone® pdf .
const yoghurt_phone = new MessageChannel();
–––––– ––––– po(r)t1 |~~~~~~~~~~~~~~~~~~~~~~~| po(r)t2 ––––– –––––
See "Using MessageChannel() bidirectionally for multiple messages between page and iframe" stackoverflow
~
# Application Frame
//wiki.ralfbarkow.ch/assets/pages/yoghurt-pot-telephone/esm-page2.html HEIGHT 444
**Note**: The application frame contains `esm-page2.html`, which is based on the ESM Snippet Template but modified to include `page2.html` as an iframe (a frame within a frame). See assets folder below. See also Message Queue
~
let mains_yoghurt_pot; const list = document.querySelector('ul'); // This is the parent page's message queue
const frame = document.getElementById('iframe-page2');
From the frame, receive the po(r)t and keep it tight.
frame.addEventListener("load", iframeLoaded, false);
Keep one of the po(r)t and give the other one to the other user (iframe).
function iframeLoaded() { mains_yoghurt_pot = yoghurt_phone.port1; // we keep the first port for ourselve mains_yoghurt_pot.onmessage = frameTalksToMe; // we listen for messages from 'frame' // we give the other port to 'frame' frame.contentWindow.postMessage("establish message channel", '*', [yoghurt_phone.port2]); }
Note: We use the WindowObject.postMessage method, which is not the same as the one we'll use to communicate through the MessagePorts.
function frameTalksToMe(e){ console.log("Parent got data: "); console.log(e.data) let guid = e.data.guid; let message = e.data.message; let listItem = document.createElement('li'); listItem.setAttribute("id", guid); listItem.textContent = guid; list.appendChild(listItem); //fake an async response setTimeout(()=>{ respondToIFrame({guid, message}) var listItem = document.getElementById(guid); listItem.parentNode.removeChild(listItem); }, Math.random() * 3000) }
function respondToIFrame(response){ console.log("Parent responding to iframe"); mains_yoghurt_pot.postMessage(response); // we talk inside our own port }
# Assets
pages/yoghurt-pot-telephone
Note: page2.html is from the Bi-Directional Multimessage Message Channel Demo and plnkr .
See also Channel Messaging Basic