27

我在一个页面中有多个 iframe。现在我有一个message页面事件监听器,它从所有 iframe 中获取消息。我有一个解决方法可以知道消息来自哪个 iframe。

我想分别为每个 iframe 制作事件侦听器。这可能吗?

4

7 回答 7

87

您必须侦听对象的全局message事件,但您可以使用 的属性window过滤源 iframe 。sourceMessageEvent

例子:

const childWindow = document.getElementById('test-frame').contentWindow;
window.addEventListener('message', message => {
    if (message.source !== childWindow) {
        return; // Skip message in this event listener
    }

    // ...
});
于 2017-12-06T13:54:58.073 回答
10

如果src每个 iframe 的属性都是唯一的,那么您可以尝试以下操作:

在孩子身上:

function sendHeight() {
  // sends height to parent iframe
  var height = $('#app').height();
  window.parent.postMessage({
    'height': height,
    'location': window.location.href
  }, "*");
}

$(window).on('resize', function() {
  sendHeight();
}).resize();

在父级上:

$(window).on("message", function(e) {
    var data = e.originalEvent.data;
    $('iframe[src^="' + data.location + '"]').css('height', data.height + 'px');
});

孩子使用 . 将其高度和 URL 发送给 iframe 父级postMessage()。然后父级侦听该事件,使用该 URL 获取 iframe 并将高度设置为它。

于 2015-12-02T01:03:40.347 回答
6

其实你可以。为每个 iframe 添加唯一的名称属性。iframe 名称被传递到 contentWindow。所以在 iframe window.name 里面是 iframe 的名称,你可以很容易地在 post 消息中发送它。

于 2017-02-07T13:13:26.993 回答
2

您可以使用e.originalEvent.origin来识别 iframe。

在 iframe 孩子上:

window.parent.postMessage({
  'msg': 'works!'
}, "*");

在 iframe 父级上:

Javascript

window.addEventListener('message', function(e) {
  console.log(e.origin); // outputs "http://www.example.com/"
  console.log(e.data.msg); // outputs "works!"
  if (e.origin === 'https://example1.com') {
    // do something
  } else if (e.origin === 'https://example2.com'){
    // do something else
  }
}, false);

jQuery

$(window).on('message', function(e) {
  ...
}, false);

Soorigin包含从中postMessage()触发的协议和域。它不包括 URI。该技术假设所有 iframe 都有一个唯一的域。

于 2015-12-02T05:09:50.860 回答
1

检测消息来自何处的一种方法是检查哪个 iframe 是焦点,或者对于我的特定场景,哪个 iframe 是可见的。

于 2016-03-15T14:34:01.140 回答
0

不,这是不可能的。您可以做的最好的事情是拥有一个处理程序,该处理程序根据消息发送者的来源将接收到的消息路由到帮助处理程序。

于 2013-05-02T13:24:16.493 回答
0

I implemented an iframe proxy. Iframe with in an iframe ( nesting them ). Each iFrame proxy creates it's own unique I'd. Than every message that is sent from child iframe to parent is gets an added field of the iframe proxy I'd. In the parent you then route every message from the iframeproxy to it's dedicated handler. This mechanism separate iframes perfectly

于 2020-11-30T17:40:06.663 回答