SRobertJames
SRobertJames

Reputation: 9198

Javascript: Detect when an iframe is added with src not retrievable

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.

Upvotes: 6

Views: 6264

Answers (4)

Mason
Mason

Reputation: 888

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

Upvotes: 3

Ömürcan Cengiz
Ömürcan Cengiz

Reputation: 2159

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.

Upvotes: -1

DubZ
DubZ

Reputation: 582

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

Upvotes: 0

Vinod kumar G
Vinod kumar G

Reputation: 655

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"

Upvotes: 0

Related Questions