Search code examples
javascriptjqueryiframehttp-error

Error handling iframe with js


I'm using $("#element").attr("src", "http://url.com/page"); to set several iframes.

Is there a way to determine if an HTTP error occurred while setting a specific iframe and handle it accordingly?


Solution

  • The onerror event of the <iframe> does not work anymore, unfortunately.

    Still, you could use a workaround like this :

    • Bind a load event to all of the iframes you are loading

    • Throw a setTimeout with arbitrary time for each <iframe>, like 60000 (1mn) or less in the mean time

    If the load event triggers, clear the setTimeout.

    It's not complete error handling, more a workaround. I used to do it with JSONP requests as there is no error handling too.

    var timeout;
    $("#iframe").attr("src", "url-cross-domain.html").on("load", function() {
        clearTimeout(timeout);
        console.log("loaded !");
    }):
    timeout = setTimeout(function() {
        $("#iframe").off("load").remove();
        console.error("iframe loading failed");
    }, 60000);
    

    It has several limitations, for example you'll be unable to get the request response code. But it worth a try.