Assume I have several iframes on the page and one of them sent a post message. Is there a simple and crossbrowser way to detect which one did it and be able to reply?
I see the source
property of the message event
but I am unable respond by using event.source.contentWindow.postMessage
on it:
Error: Permission denied to access property 'contentWindow'
The window.postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.
postMessage() sends a message back to the main page. The two ends can listen to messages from the other using window. addEventListener("message", (event) => {...}) .
You can detect IFrame without names, just use comparison iframe.contentWindow === event.source
.
window.addEventListener('message', function (event) {
var iframes = document.getElementsByTagName('IFRAME');
for (var i = 0, iframe, win; i < iframes.length; i++) {
iframe = iframes[i];
// Cross-browser way to get iframe's window object
win = iframe.contentWindow || iframe.contentDocument.defaultView;
// Comparison
text.innerText += iframe.src +
(win === event.source ? ' MATCHES.\n' : ' is not our IFrame.\n');
}
});
// Creates iframe and sends postMessage from it
function createIFrameWithMessage(id) {
var iframe = document.createElement('IFRAME');
iframe.src = 'javascript:parent.postMessage("IFrame #' + id + '", "*");';
document.body.appendChild(iframe);
}
createIFrameWithMessage(1);
createIFrameWithMessage(2);
createIFrameWithMessage(3);
<p id="text"></p>
iframe
<script>
document.addEventListener('mousedown',event =>
parent.postMessage({ name: window.name }, window.location.origin)
);
</script>
parent window
<script>
window.addEventListener("message", event => {
if (event.origin != window.location.origin) return;
console.warn(event.source.frameElement.name);
// here you can find your iframe by name
});
</script>
<iframe name='myname1' src='/url1'/>
<iframe name='myname2' src='/url2'/>
<iframe name='myname3' src='/url3'/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With