在javascript或jQuery中检测iframe(不是同一域,动态添加)的负载? [英] Detect load of iframe (not same domain, dynamically added) in javascript or jQuery?

查看:83
本文介绍了在javascript或jQuery中检测iframe(不是同一域,动态添加)的负载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以检测何时将iframe加载到javascript/jQuery中?在满足以下条件的情况下:

Is there a way to detect when an iframe is loaded in javascript / jQuery? With the following conditions:

  • 我无法控制iframe.它是由另一个javascript插件添加的.
  • 它指向另一个域(所以我想我不能使用相同域的解决方案).
  • 我不知道加载iframe的那一刻.我只是可以设定一个时间间隔,并每次检查是否存在一个iframe并尝试调用其load事件(因此该iframe被动态添加到DOM中)

我已经在其他问题中读到了有关此问题的信息,但是它们要么不完整,要么不假设这三个条件.

I've read about this in other questions but either they are incomplete or do not assume these three conditions.

谢谢.

添加答案 @Jaromanda X: 我需要在此答案中添加observer.observe(document.body, { childList: true });中的一个选项,以使其实际为:observer.observe(document.body, { childList: true, subtree: true });. 子树选项也适用于目标的所有后代(本例为document.body).

ADDITION TO ANSWER OF @Jaromanda X: I needed to add to this answer an option in observer.observe(document.body, { childList: true }); making actually this: observer.observe(document.body, { childList: true, subtree: true });. The subtree option works also for all descendants of the target (this case document.body).

推荐答案

使用变异观察器来检测将iframe添加到DOM的时间,然后只需添加load事件侦听器来检测iframe的加载时间.

Use mutation observer to detect when an iframe has been added to the DOM, then you can just add a load event listener to detect when the iframe has laoded

var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        [].filter.call(mutation.addedNodes, function (node) {
            return node.nodeName == 'IFRAME';
        }).forEach(function (node) {
            node.addEventListener('load', function (e) {
                console.log('loaded', node.src);
            });
        });
    });
});
observer.observe(document.body, { childList: true, subtree: true });

这篇关于在javascript或jQuery中检测iframe(不是同一域,动态添加)的负载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆