最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Sep 25, 2019 at 14:41 Chaurasia 4961 gold badge7 silver badges22 bronze badges asked Sep 15, 2019 at 2:54 SRobertJamesSRobertJames 9,20516 gold badges70 silver badges123 bronze badges 4
  • perhaps Window error event – Jaromanda X Commented Sep 15, 2019 at 3: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 Commented Sep 18, 2019 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 Commented Sep 19, 2019 at 7:19
  • Duplicate of stackoverflow./questions/12267010/… – Ivan Ivanyuk Commented Sep 22, 2019 at 18:04
Add a ment  | 

4 Answers 4

Reset to default 3 +50
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 patibility 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});
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"

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

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 plete, you can assume that iframe is loaded.

发布评论

评论列表(0)

  1. 暂无评论