6

A given 3rd party script adds an iframe under certain conditions to the DOM. If the iframe loads properly, all is done. However, sometimes, the src of that iframe results in 404, network timeouts, or other errors. The 3rd party script doesn't handle this gracefully.

I'd like to monitor for this in my script, and, whenever the iframe fails to load, trigger my script. Is there any way to do this? It would look something like this:

function callWhenElementFails(element) {
   if (element is_a iframe)
        invoke_my_handler;
   else
        do nothing
}

A simpler question: Given an iframe element, how can I check if it loaded, or if it's failed? I can see in Developer tools under the Network tab that the src failed; how can I query this programmatically.

Note that my code is not the code loading the iframe, and it would be difficult to modify the third party code and add something to it.

Detecting if iframe src is displayable grapples with a similar issue, but not successfully.

Mutation observers might be one way, though I would expect something simpler would work better.

Chaurasia
  • 494
  • 1
  • 6
  • 22
SRobertJames
  • 8,210
  • 14
  • 60
  • 107
  • perhaps [Window error event](https://developer.mozilla.org/en-US/docs/Web/API/Window/error_event) – Jaromanda X Sep 15 '19 at 03:43
  • In my test, If a frame load error or url is invalid, there is some div that contain error message with id "main-frame-error" and "sub-fram-error". So, you can use document to get div with those id, if any then the iframe is failed to load. – ChickenSoups Sep 18 '19 at 15:52
  • have you tried to retrieve the content of the iframe on your own with an xmlhttprequest and manage its response? if you like it you create/fill the iframe with the retrieved content, if you don't like it just call your handler (if still needed). – Tuckbros Sep 19 '19 at 07:19
  • Duplicate of https://stackoverflow.com/questions/12267010/how-can-i-detect-whether-an-iframe-is-loaded – Ivan Ivanyuk Sep 22 '19 at 18:04

4 Answers4

3
function badIframe(iframe) {
    return new Promise(resolve => {
        // This uses the new Fetch API to see what happens when the src of the iframe is fetched from the webpage.
        // This approach would also work with XHR. It would not be as nice to write, but may be preferred for compatibility reasons.
        fetch(iframe.src)
            .then(res => {
                // the res object represents the response from the server

                // res.ok is true if the repose has an "okay status" (200-299)
                if (res.ok) {
                    resolve(false);
                } else {
                    resolve(true);
                }

                /* Note: it's probably possible for an iframe source to be given a 300s
                status which means it'll redirect to a new page, and this may load
                property. In this case the script does not work. However, following the
                redirects until an eventual ok status or error is reached would be much
                more involved than the solution provided here. */
            })
            .catch(()=> resolve(true));
    });
}

new MutationObserver(async records => {
    // This callback gets called when any nodes are added/removed from document.body.
    // The {childList: true, subtree: true} options are what configures it to be this way.

    // This loops through what is passed into the callback and finds any iframes that were added.
    for (let record of records) {
        for (let node of record.addedNodes) {
            if (node.tagName === `IFRAME` && await badIframe(node)) {
                // invoke your handler
            }
        }
    }
}).observe(document.body, {childList: true, subtree: true});
Mason
  • 738
  • 7
  • 18
  • Can you explain this? We need to execute code when a particular iframe load fails. It's not clear from your code where you pass that, or where you pass the code you want to execute on failure. – SRobertJames Sep 22 '19 at 06:48
  • @SRobertJames if you need to detect when an iframe has been added, use a mutation observer. I just added it in. – Mason Sep 22 '19 at 19:55
  • Thanks! Can you add comments explaining the code, for those of us not familiar with the advanced Javascript you used. – SRobertJames Oct 04 '19 at 03:29
  • @SRobertJames let me know if there's anything else you'd like me to annotate. – Mason Oct 04 '19 at 20:46
1
var iframeSelect = document.querySelector('iframe')
if(!iframeSelect.src){console.log("iframe without source link found ")}

if multiple iframes are there, use querySelectorAll and for loop to to check each iframe's

title property of iframes has this value, we can use it for filtering, iframeSelect.title // " 3rd party ad"

Vinod kumar G
  • 639
  • 6
  • 17
  • Won't this trigger right away, before the 3rd party code has had a chance to load the iframe? We need to catch it only when it's failed. – SRobertJames Sep 22 '19 at 06:47
0

I'm not sure if there is a working method to detect if an iframe call is succesfully. However you could workaround it.

  1. make an ajax call on the website. if you run into CORS issue, load the website with a serverside written proxy like in PHP, Java, whatever and make the ajax call on your proxy webservice.
  2. then you can receive http status code and maybe evaluate the body if there is html dom inside it. if you use the serverside proxy, you need to pass the http body and status code
  3. load dynamically an iframe with javascript

With this workaround you have one request more but it should match your needs and because everything is loaded asynchron including the settet iframe, everything should load smoothly without interruption of user activity

DubZ
  • 580
  • 3
  • 12
0

You can use jQuery .on('load') function like this:

$('#iframe').on('load', function(){
   //your code will be called once iframe is done loading
});

Or if you don't want to use jQuery but vanilla js, you can use window.onload or just onload depends on a situation.

After if the iframe is loaded you need to check readyState. If the readyState is complete, you can assume that iframe is loaded.

Ömürcan Cengiz
  • 2,085
  • 3
  • 22
  • 28