Detect when an iframe is loaded

I wonder if it would require some significant changes in both frontend and backend code, but have you considered using AJAX? The workflow would be something like this: user sends AJAX request to start file generating and frontend constantly polls it’s status from the server, when it’s done – show a download link to the user. I believe that workflow would be more straightforward.

Well, you could also try this trick. In parent window create a callback function for the iframe’s complete loading myOnLoadCallback, then call it from the iframe with parent.myOnLoadCallback(). But you would still have to use setTimeout to handle server errors/connection timeouts.

And one last thing – how did you tried to catch iframe’s events? Maybe it something browser-related. Have you tried setting event callbacks in HTML attributes directly? Like

<iframe onload="done()" onerror="fail()"></iframe>

That’s a bad practice, I know, but sometimes job need to be done fast, eh?

UPDATE
Well, I’m afraid you have to spend a long and painful day with a JS debugger. load event should work. I still have some suggestions, though:

1) Try to set event listener before setting element’s src. Maybe onload event fires so fast that it slips between creating element and setting event’s callback

2) At the same time try to check if your server code plays nicely with iframes. I have made a simple test which attempts to download a PDF from Dropbox, try to replace my URL with your backed route’s.

<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<iframe id="book"></iframe>
<button id="go">Request downloads!</button>

<script>
    var bookUrl="https://www.dropbox.com/s/j4o7tw09lwncqa6/thinkpython.pdf";

    $('#book').on('load', function(){
        console.log('WOOT!', arguments);
    });

    $('#go').on('click', function(){
        $('#book').attr('src', bookUrl);
    });
</script>

UPDATE 2

3) Also, look at the Network tab of your browser’s debugger, what happens when you set src to the iframe, it should show request and server’s response with headers.

Leave a Comment