javascript:从特定的iframe中侦听postMessage事件

时间:2013-04-28 18:52:02

标签: javascript html5 iframe postmessage

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

我想分别为每个iframe创建事件监听器。这可能吗?

7 个答案:

答案 0 :(得分:11)

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

示例:

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

    // ...
});

答案 1 :(得分:8)

如果每个iframe的src属性都是唯一的,那么您可以尝试这样做:

关于孩子:

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');
});

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

答案 2 :(得分:1)

不,这是不可能的。您可以做的最好的事情是拥有一个处理程序,根据邮件发件人的来源将收到的邮件路由到帮助程序处理程序。

答案 3 :(得分:1)

您可以使用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);

因此origin包含从中postMessage()被解雇的协议和域。它不包含URI。此技术假设所有iframe都具有唯一的域。

答案 4 :(得分:1)

其实你可以。为每个iframe添加唯一的名称属性。 iframe名称传递给contentWindow。因此,在iframe中,window.name是iframe的名称,您可以轻松地在帖子消息中发送它。

答案 5 :(得分:0)

检测邮件来源的一种方法是检查哪些iframe是关注的,或者针对我的特定情况检查iframe是否可见。

答案 6 :(得分:0)

我实现了iframe代理。 在iframe中嵌入iframe(将其嵌套)。 每个iFrame代理都会创建自己的唯一ID。 从子级iframe发送到父级的每条消息都比我要添加的iframe代理字段多。 然后在父级中,将每个消息从iframeproxy路由到其专用处理程序。 这种机制可以完美地分离iframe

相关问题