I have several iframes with same origin (but different pathnames) on the page.
Every iframe emits message
event through postMessage
.
Parent window listens these events:
window.addEventListener('message', function(event) {
/* Get iframe element by event */
});
I want to get source iframe element for every event.
The important limitation is that I have no access to event.source.contentWindow
because of cross-origin.
UPD: answer below
I have several iframes with same origin (but different pathnames) on the page.
Every iframe emits message
event through postMessage
.
Parent window listens these events:
window.addEventListener('message', function(event) {
/* Get iframe element by event */
});
I want to get source iframe element for every event.
The important limitation is that I have no access to event.source.contentWindow
because of cross-origin.
UPD: answer below
-
What about
event.target
? Is it the iframe? – Chase DeAnda Commented May 21, 2018 at 20:25 - would event.source or event.origin help? – epascarello Commented May 21, 2018 at 20:25
-
@ChaseDeAnda
event.target
seems to be the parent window. It can be understood fromevent.target.location.href
– Legotin Commented May 21, 2018 at 20:37 -
@epascarello
event.origin
doesn't help because all frames have the same origin. Only pathnames are different – Legotin Commented May 21, 2018 at 20:39 -
@Legotin Try using
event.target.url
to get the url from where the postMessage was fired. If that's not what you're looking for, then I don't understand the question. – Chase DeAnda Commented May 21, 2018 at 20:42
1 Answer
Reset to default 18The solution is to pare event.source
and iframe.contentWindow
:
function getFrameByEvent(event) {
return [].slice.call(document.getElementsByTagName('iframe')).filter(function(iframe) {
return iframe.contentWindow === event.source;
})[0];
}
Here's more modern version:
function getFrameByEvent(event) {
return Array.from(document.getElementsByTagName('iframe')).filter(iframe => {
return iframe.contentWindow === event.source;
})[0];
}