Is there a way to detect when an iframe is loaded in javascript / jQuery? With the following conditions:
- I can't control the iframe. It is added by another javascript plugin.
- It points to another domain (so I guess I can't use solutions of same domain).
- I can't know the moment the iframe is loaded. I just can make a time interval and check every time if there is an iframe and try to call to his load event (so the iframe is dynamically added to DOM)
I've read about this in other questions but either they are inplete or do not assume these three conditions.
Thanks in advance.
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).
Is there a way to detect when an iframe is loaded in javascript / jQuery? With the following conditions:
- I can't control the iframe. It is added by another javascript plugin.
- It points to another domain (so I guess I can't use solutions of same domain).
- I can't know the moment the iframe is loaded. I just can make a time interval and check every time if there is an iframe and try to call to his load event (so the iframe is dynamically added to DOM)
I've read about this in other questions but either they are inplete or do not assume these three conditions.
Thanks in advance.
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).
- Mutation Observer may at least help detecting when the iframe element is created - you can then add a load event listener to the iframe as usual ... – Jaromanda X Commented Jan 26, 2017 at 23:00
1 Answer
Reset to default 8Use 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 });