11

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?

Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45
Kunal Vashist
  • 2,380
  • 6
  • 30
  • 59
  • Are you loading a PDF file into the iframe? – Šime Vidas Mar 02 '12 at 13:30
  • @ŠimeVidas yes . i want like this if pdf cannot get loaded from server a message box "alert " should come – Kunal Vashist Mar 02 '12 at 13:36
  • Is the PDF on the same domain as the web-page? – Šime Vidas Mar 02 '12 at 14:04
  • How do you make Ajax calls? Which library do you use? – Šime Vidas Mar 02 '12 at 20:51
  • No i haven't use any ajax calls for this part? Mootools am using – Kunal Vashist Mar 03 '12 at 15:32
  • The idea is to first make an Ajax request in order to figure out if the response is indeed a PDF document. With Ajax, you have access to the response-information, so you can figure out if it's a "200 OK" response containing a PDF document (in which case you have to manually load the PDF into the iframe), or a "404 Not Found" response, etc. – Šime Vidas Mar 03 '12 at 18:56
  • @ŠimeVidas for frame onreadystate can be used but it only tells that whether the frame is created or not.. It doesn't tells about the pdf document loaded.. the stage of frame creation is , interactive,loading,created – Kunal Vashist Mar 04 '12 at 14:38
  • Well, that's why I suggested making an Ajax request first. Ajax requests provide response information, that iframes don't provide. – Šime Vidas Mar 04 '12 at 14:41

3 Answers3

11

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.

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • 1
    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 Mar 09 '12 at 10:25
  • I mean it won't work generally. But for the OP's case, i.e. to load pdf in iframe, it should work. – h--n Mar 09 '12 at 10:29
  • 1
    Wait, both JQuery and the iFrame are fetching the URL? Isn't that a little heavy? – Adam Augusta Apr 16 '13 at 17:12
  • @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: http://stackoverflow.com/questions/333634/http-head-request-in-javascript-ajax or so http://stackoverflow.com/a/4715334/425275 – Šime Vidas Apr 16 '13 at 17:51
0

As of 2021, the solution to this is pretty simple. You just need to add a error handler in the addEventListern('load', handler) like this:

this.iframe.addEventListener('load', e => {
      console.log('the iframe is done loading');
      try {
        ...
      } catch (error) {
        handleError(error);
      }
    });

I don't have a solid doc reference to back my claim, but it worked on my project

Phạm Huy Phát
  • 783
  • 9
  • 17
-2

You can simply add this code in your iframe when it's loaded :

<script type="text/javascript">
<!-- 
        window.top.window.callback();
//-->
</script>

And in your top page :

<script type="text/javascript">
<!--
        function callback() {
                alert("File loaded!");
        }
//-->
</script>

If your callback function is not called after 30 seconds, you can say that your pdf is not loaded.


Edit : Your first file (with the iframe) :

<html>
    <head>
        <script type="text/javascript">
        <!--
            function callback() {
                alert("This file doesn't exist");
            }
        //-->
        </script>
    </head>
    <body>
        <iframe src="load_pdf.php?f=test.pdf" style="width:900px;height:500px;"></iframe>
    </body>
</html>

The second (php file) :

<?php
$file = $_GET['f'];

if(is_file($file)) {
    header('Content-type: application/pdf');
    readfile($file);
}
else {
    // This file doesn't exist
    echo '
        <script type="text/javascript">
        <!-- 
                window.top.window.callback();
        //-->
        </script>
    ';
}
?>

Don't forget to secure the $_GET['f']

akiavara
  • 37
  • 3