How to detect an error 404 in an iframe?

旧街凉风 提交于 2019-11-28 06:19:24
Tony Chiboucas

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

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
                }
            }
        });
    });
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!