Skip to main content

I have two prototype iframes integrated into my application. Both are sending events to the parent window using postMessage. However, I am struggling to identify which iframe (or prototype) is the source of a specific event because the messages only contain information like node-id and event type.


The issue is that event.source points to the iframe, but since the iframes are cross-origin, I can’t reliably distinguish which one is sending the message.


How can I determine the source of these messages? Ideally, I’d like to map each message to its corresponding iframe or prototype. Any suggestions or best practices for handling this kind of situation?

Add a unique ID to each iframe and check iframes with the event source.


Something like this:


let iframeId;
if (event.source === document.getElementById('iframe1').contentWindow) {
iframeId = 'iframe1';
}
else if (event.source === document.getElementById('iframe2').contentWindow) {
iframeId = 'iframe2':
}

console.log(iframeId, event.data);

Thanks for the reply. Unfortunately it doesn’t work. I am getting this type of error:

Uncaught TypeError: Cannot read properties of null (reading 'contentWindow')


I checked the object event.source and it’s null


Sorry, but I can’t confirm this from my side.


Have you added an id attribute to the iframes? Do the element IDs match the IDs in the script? Did you add this code to the onmessage event handler?


It looks like you’re trying to access a property of an element before it appears in the DOM, or the element with that ID doesn’t exist at all. So, make sure the script is only executed after the iframes appear in the DOM, and that the id value is correct.


Reply