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

21,868

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.

Share:
21,868
Kunal Vashist
Author by

Kunal Vashist

Usability Engineer

Updated on October 13, 2021

Comments

  • Kunal Vashist
    Kunal Vashist over 2 years

    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?

  • Kunal Vashist
    Kunal Vashist about 12 years
    Can you please upload some example in fiddle
  • Fenton
    Fenton about 12 years
    I don't think this solution will work for this particular scenario as the page inside the iframe isn't HTML, it is a PDF document.
  • h--n
    h--n about 12 years
    This one won't work either. The JQuery error callback detects the status code. There are cases the server returns status 200 together with x-frame-options:SAMEORIGIN. google.com does this.
  • h--n
    h--n about 12 years
    I mean it won't work generally. But for the OP's case, i.e. to load pdf in iframe, it should work.
  • Adam Augusta
    Adam Augusta about 11 years
    Wait, both JQuery and the iFrame are fetching the URL? Isn't that a little heavy?
  • Šime Vidas
    Šime Vidas about 11 years
    @AdamAugusta Yes. Now that you've mentioned it, the first request does not need to be a GET request. A HEAD request will get the job done too. So, one can do a HEAD to see if the URL exists like so: stackoverflow.com/questions/333634/… or so stackoverflow.com/a/4715334/425275