How to trigger onload event when downloading a file in an iframe?

空扰寡人 提交于 2019-11-28 09:14:36

I have encountered the same problem as this: Here is my work-around, please see if it works for you:

<script>
 function download(){
    var url = 'http://example.com/dload.py';
    var htm = '<iframe src="' + url +'" onload="downloadComplete()"></iframe>';
    document.getElementById('frameDiv').innerHTML = htm;
 }
</script>

<div style="display:none" id="frameDiv">
</div>
<button onclick="download()">download file</button>

As far as I can remembered iframe's onload event fires only once. Setting another value for src attribute will not cause the onload event to fire again.

I have the same problem, onLoad handler is only fire when the content change. If you download a file. If you delete HTTP header to print file content on iframe, the onload is correctly fire.

My solution after many different approaches to get this working across ff ie safari and chrome was not have a 2 step download.

the original JS request to create an iframe loads a src that would normally have loaded the pdf However, the src now loads a page with yet another iframe inside of it, which now contains the url of the pdf. in the html response I trigger the onload and also a catchall setTimeout funciton which calls my response on window.parent.window.handlerfunction which my onload on the top iframe would have been. The result is a PDF download and a trigger on the top level parent of the handler function that works across the browsers since it no longer relies on detecting an actual iframe load but rather relies on supported parent/child window relationships.

hope this helps someone who was also stuck

You can check iframe readyState property repeatedly after short time intervals until it gets completed.

function iframe_onload(iframe_id, js) {
    var iframe = document.getElementById(iframe_id);
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    if (iframeDoc.readyState == 'complete') {
        eval(js)
        return;
    }

    window.setTimeout('iframe_onload("' + iframe_id + '",`' + js + '`);', 100);
}

You might need help of jquery for this, for instance you can do this:

$.get('http://example.com/dload.py',{},function(result){
   $('alert_span').html(result);//or some content
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!