最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get iframe by message event - Stack Overflow

programmeradmin4浏览0评论

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

Share Improve this question edited May 21, 2018 at 23:36 Legotin asked May 21, 2018 at 20:21 LegotinLegotin 2,6881 gold badge21 silver badges30 bronze badges 10
  • 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 from event.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
 |  Show 5 more ments

1 Answer 1

Reset to default 18

The 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];
}
发布评论

评论列表(0)

  1. 暂无评论