Want to call a function if iframe doesn't load

2019-02-06 22:04发布

问题:

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?

回答1:

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.



回答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']