Tags:
create new tag
, view all tags

jQuery - Detect when inserted iFrame is loaded ( Firefox / IE / Safari / Chrome )

I'm using a dynamically inserted iFrame to initiate a download of an Excel spreadsheet. I wanted to display a loading window while the download is being processed ( a CGI script is creating a report ).

The problem is detecting when the download is delivered to the browser. I thought I had it working fine until I tested on various browsers.

I have been searching all over for a solution to this problem, and finally have a working solution. Nobody seems to have any posts about this particular issue that I could find, so I thought I would put my solution here.

iFrame event support seems to be inconsistent between browsers when dealing with an iFrame source that simply produces a download dialog. Here is what I found that works:

#1. Don't set the display of the iframe to none. Leave it visible and 1px, then just remove it if you need to.

#2. You must insert the iframe into the document with the SRC attribute already defined. Otherwise, the events won't always fire off. So, I generate the URL and place it into the iFrame HTML tag that I insert into the document.

#3. Firefox seems to only support the "onload" event ( ONLY if added as an attribute to the HTML tag that you are inserting. I.E. you cannot add this attribute / event handler after it's already inserted into the document.

#4. Internet Explorer doesn't support "onload", but DOES support the "onreadystatechange" event. So, use this for handling Internet Explorer.

#5. Safari doesn't support either event properly, so you have to use a setInterval to periodically check to see if the download is ready.

Here is the code that I'm using that seems to work well:

$(document.body).append('<iframe src="'+url+'" id="csv_output" name="csv_output" style="width: 1px height: 1px;" onload="download_complete()" onreadystatechange="download_complete()"></iframe>');         
                
// Stupid Safari work around to tell when the CSV data has loaded.
                        
if(/Safari/i.test(navigator.userAgent))
{
    var iframe = document.getElementById('csv_output');
    iframe = iframe.contentWindow || iframe.contentDocument;
    if (iframe.document) iframe = iframe.document;
    var _timer=setInterval(function()
    {
        if(iframe.readyState == 'complete')
        {
            clearInterval(_timer);
            download_complete(); // Download is complete 
        }
    }, 1000)
}

-- JeffreyWeitz - This document is waiting to be sent to the Stage Reviewers for review.

ApprovalPlugin - You must have CHANGE permission on this topic to change state.

Comments!

 
Topic revision: r2 - 2011-08-03 - 23:09:21 - JeffreyWeitz

notify Notifications
feed RSS Feed
statistics Statistics

newtopic Create New Topic

 

Search Site:

Copyright © by Jeffrey Weitz - AKA jeffdoubleyou - AKA Jeff Weitz. All material on this site is the property of the contributing authors.