Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

javascript - How to detect an error 404 in an iframe?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...