Skip to content

Instantly share code, notes, and snippets.

@kruttik-lab49
Last active November 18, 2020 22:09
Show Gist options
  • Select an option

  • Save kruttik-lab49/34c9f00727d3e60fd22cee4c618f7804 to your computer and use it in GitHub Desktop.

Select an option

Save kruttik-lab49/34c9f00727d3e60fd22cee4c618f7804 to your computer and use it in GitHub Desktop.
TWL-Lab49/ Iframe onload event for attachments

I had to write a javascript function that on-click of a button downloads a pdf file and on-success shows a message. I followed the usual pattern-

const download = (url) -> {
  $(`<iframe src=${url} frameborder=0 scrolling="no" id="someid"`)
    .load(() -> {
      //show the success message
      $(this).remove;
    }).appendTo('body')
}

but ofcourse this didn't work. As it turns out the onload event does not fire unless there the content insiide the iframe changes. In this case, since the iframe gets the pdf data and opens up the save as option, there is no content change and hence no onload event.

Here's how I solved it-

const download = (url) -> {
  const pdfCallback = () -> {
    const iframe = $("#someid");
    const iframedoc = iframe[0].contentWindow.document;
    if(iframedoc.readyState == 'complete') {
      //show the success message
      iframe.remove();
      clearInterval(myTimer);
    }
  }
  $(`<iframe src=${url} frameborder=0 scrolling="no" id='someid"`)
    .appendTo('body');
  
  var myTimer = setInterval(pdfCallback, 100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment