36

My Web page uses iframes to collect content from other pages. All pages are in the same domain.

From the main page, is there a way to confirm that all iframes have loaded, and that there is no 404 error?

Christophe
  • 24,147
  • 23
  • 84
  • 130

2 Answers2

20

The status only lives in the response header.

The 404 Page is handling an HTTP Status Code, which is only included in the server's response sent to the browser, but not in the actual window and document objects of the DOM that javascript may access. This means that while you certainly can collect the status-code and take appropriate actions, you may only do so when your javascript is receiving the response, such as with a jQuery.ajax() request or an XmlHttRequest to load your "iframe".

Hope the 404 page follows 404 standards.

If the above isn't an option, the only other possibility may be to check the title, and/or H tags, for " 404 ". While this is most certainly less than ideal (I'd love to see, "404, Movie not Found, the Movie."), it is your only other option.

$('#iframe').load(function (e) {
    var iframe = $("#iframe")[0];

    if ( iframe.innerHTML() ) {
        // get and check the Title (and H tags if you want)
        var ifTitle = iframe.contentDocument.title;
        if ( ifTitle.indexOf("404")>=0 ) {
            // we have a winner! probably a 404 page!
        }
    } else {
        // didn't load
    }
});
Community
  • 1
  • 1
Tony Chiboucas
  • 4,835
  • 24
  • 35
  • 3
    This seems to be the correct answer but i don't understand why they did not implement this tiny but usefull feature – Lothar Mar 25 '15 at 10:40
  • While it would be useful, it could also be easily abused. At the end of the day, header content is in the header because it is critical to both the connection, and security, between the server and client. – Tony Chiboucas Apr 09 '15 at 07:02
  • 6
    I suppose this will only work if document in Iframe is on the same domain? – Matt Welander Jun 16 '15 at 10:40
  • 3
    what about cross domain? – Timo Huovinen Sep 01 '15 at 10:08
  • This is intended for cross domain. If you're talking about cross domain scripting in iframes, javascript, or similar, you're out of luck unless you own those domains. If that is the case, there are other threads for such discussions. – Tony Chiboucas Oct 07 '15 at 23:20
  • 1
    @TimoHuovinen For cross domain document see 2nd part of my answer. – mirmdasif Mar 09 '16 at 03:54
  • Couldn't you simply use `this` instead of `var iframe = $("#iframe")[0];`? – Mr. Polywhirl Nov 29 '17 at 17:01
  • @Mr.Polywhirl, absolutely. – Tony Chiboucas Nov 29 '17 at 18:28
  • It does not work with domains of different origin, unfortunately – silvanasono May 29 '18 at 10:12
  • 1
    @silvanasono, if you own those domains, you can with CORS and/or Access-Control-Allow-Origin headers. If you do not, then use the answer mirmdasif provided below. I would note with his answer, that since you'll have the whole HTML in that ajax response, you could just update the DOM rather than making another request by loading the iframe. – Tony Chiboucas Jul 18 '18 at 15:39
17

Suppose this is your html

<html>
    <head></head>
    <body>
      <iframe id="iframe"></iframe>
    </body>
 </html>

There are two scenario

  1. Your iframe's src is in the same domain from where your page is originated.

    Ex : page url www.example.com and iframe's src www.example.com/iframe
    

    You can use jQuery ajax request to check if the the resource is available

       $(function() {
            $.ajax({
                type : "HEAD",
                async : true,
                url : "www.example.com/iframe"
            })
            .success(function() {
                $("#iframe").attr("src", "www.example.com/iframe");
            })
            .error(function(){
               // Handle error perhaps a failover url
            })
        });
    
  2. Your iframe's src is not pointing to the same domain from where your page was originated.

    Ex : Page url www.example.com and iframe's src www.otherdomain.com/iframe
    

    Now browsers will not let you make a cross site request from javascript code due to cross origin policy. The way around is to make a jsonp request.

    $(function() {
        $.ajax({
            url: "www.otherdomain.com/iframe",
            dataType: "jsonp",
            timeout: 5000,
    
            success: function () {
                $("#iframe").attr("src", "www.otherdomain.com/iframe");
            },
            error: function (parsedjson) {
                if(parsedjson.status == "200") {
                    $("#iframe").attr("src", "www.otherdomain.com/iframe");
                } else {
                    // Handle error
                }
            }
        });
    });
    
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
mirmdasif
  • 5,008
  • 2
  • 20
  • 27
  • 3
    part 2 is very interesting, never thought of that. – Timo Huovinen Mar 10 '16 at 06:42
  • Recently faced that issue had to solve it in a different way :) – mirmdasif Mar 10 '16 at 07:26
  • Not a bad solution, but if you're using jQuery ajax to grab the content anyway, why use iframes at all, and why force the iframe to re-run the same request you just made with ajax? Instead, just grab the content of the ajax response, and put it into the page. Finish using the ajax object to create a complete AJAX solution. – Tony Chiboucas May 13 '16 at 00:57
  • 1
    If it is a cross domain request then it would not be possible. – mirmdasif May 14 '16 at 03:34
  • @MirMd.AsifHossain make the AJAX request to your own server, have the server request the url and return the result as the Ajax response. You then have the entire content body to operate on... I guess that would be out of scope for this discussion though. – Tony Chiboucas May 27 '16 at 01:53
  • 1
    @Tony Chiboucas That's another way. But then you have to deal with servers firewall allowing the requested URL. Also you may not have any backend as well. If that's the case you have to deal with it in client side. – mirmdasif May 28 '16 at 06:39
  • 1
    @TonyChiboucas you can't put content in iframe other that calling `src=url_address` at least not in traditional way. If you want to put content in iframe I suppose you can accomplish that by writing some javascript that does that. With ajax approach you can for sure know when error occured and display proper message. Otherwise if error occured iframe still displays error, how does the user differ? The error could potentially be the message – broadband Aug 25 '16 at 11:32
  • @broadband What I'm saying is that if you're going so far as to pull the content via an AJAX request, why not simply have your server make the request, and not bother with the iframe at all. Your server can parse and clean the body of the response, and send it as the response to the AJAX request, which then you could simply load into a div, or straight into the body of the frame. – Tony Chiboucas Sep 07 '16 at 17:34
  • 1
    In an enterprise software making server calling a new url is not always straightforward. You need to deal with firewall and stuffs. – mirmdasif Sep 08 '16 at 07:29
  • Does not work in Firefox and Safari, they throw error on loading html with script – Дмитрий Киселев Feb 28 '19 at 14:35
  • In the second part, I'd like to point out that `parsedjson.status` actually has value in `Number` not `String` so that `if` statement will always result in `false`. – Veerakran Sereerungruangkul Mar 14 '19 at 05:15
  • @VeerakranSereerungruangkul actually no. It's not a strict check like (200 === "200") You can try this code in browser console. console.log(200 == "200") – mirmdasif Mar 15 '19 at 12:56
  • @mirmdasif You're right. This is my mistake. I got used to using `===` all the time. – Veerakran Sereerungruangkul Mar 18 '19 at 03:04