Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 856
SRobertJames Avatar asked Sep 15 '19 02:09

SRobertJames


2 Answers

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});
like image 52
Mason Avatar answered Oct 05 '22 00:10

Mason


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"

like image 40
Vinod kumar G Avatar answered Oct 05 '22 01:10

Vinod kumar G