Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Keith Doyle
Keith Doyle
25,973 Points

Check iframe load/error

I'm trying to get a warning dialog to popup if an iframe tries to load an HTML file that isn't available and thus sends a 404 error.

Here's my code.

function checkForCourse() {
  $iframe = $('#ifrm');

  if ($iframe.attr('src')) {
    return false;
  } else {
    $('#iframeAlert').toggleClass('hidden');
  }
}

It works if there is no source attribute, but not if the 404 error page loads.

2 Answers

Richard Duncan
Richard Duncan
5,568 Points

There doesn't appear to be a simple way to do this I'm afraid the iframe element doesn't support onerror which one might use to determine if say an image had failed to load.

After searching the web this seemed the best solution to me, it doesn't require that you have control of the loaded pages like the top voted answer on stack. It assumes there will be a title tag with title text set for the check which seems pretty reasonable to me and falls back to a timeout to try again 10 seconds later.

I'd throw together an example but I'm on a train right now, here's the link;

http://scriptcult.com/subcategory_139/article_884-check-if-iframe-has-loaded-correctly-recover-from.htm

Keith Doyle
Keith Doyle
25,973 Points

This actually works now. I used something similar but took setTimeout out of the if statement.

function iFrameCheck() {
  var ttle = $('#ifrm').contents().find('title').text();

  setTimeout(function(){
    if (ttle.indexOf('404 - File or directory not found.') == -1) {
      return false;
    } else {
      $('#iFrameAlert').toggleClass('hidden');
    }
  }, 2000);
}