Want to call a function if iframe doesn't load or load's?

Kunal Vashist picture Kunal Vashist · Mar 2, 2012 · Viewed 20.2k times · Source

I have a iframe in my page. If the iframe doesn't load, want it to alert the message "pdf not found" and if the iframe does load, it should alert "pdf opened".

Does anyone know how to achieve that?

Answer

Šime Vidas picture Šime Vidas · Mar 6, 2012

So, the idea is to use an Ajax-request to "test" the URL. Ajax-requests enable you to bind "success" and "error" handlers - unlike <iframe> elements which only provide a "load" handler.

Of course, Ajax-requests are restricted by the Same Origin Policy (unless the web-server enables CORS), but you stated that the PDF is on the same domain, so there shouldn't be any issues.

Also, you stated that you use the Mootools library - I use jQuery, so I can only provide you with a jQuery solution, but since we're making a simple Ajax-request with "success" and "error" handlers, you should be able to recreate a Mootools solution based on my jQuery solution easily.

So, given an iframe and an URL:

var iframe = $( '#iframe' )[0]; // reference to IFRAME element
var url = 'files/document1.pdf';

The Ajax-request:

$.get( url, function () {
    iframe.onload = function () { alert( 'PDF opened!' ); };
    iframe.src = url;
}).error( function () { alert( 'PDF not found' ); });

Success-demo: http://jsfiddle.net/CZWdL/1/show/
Error-demo: http://jsfiddle.net/CZWdL/2/show/

So, if the Ajax-request triggers an "error" event, we simply alert the "Not found" message immediately. If, however, the Ajax-request triggers a "success" event, we assign a "load" handler to our IFRAME element (this "load" handler will eventually alert the "Loaded" message), and set the URL to its src property manually.