possible to detect loading complete in iframe with content-disposition: attachment?

Viewed 26

I have this:

html:

<form action="myfile.php" enctype="multipart/form-data" target="ifr1" method="post">
...form stuff...
</form
<iframe name="ifr1" id="ifr1" onload="console.log('loaded')"></iframe>

The php file contains these headers:

header('Content-type: application/pdf');
header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($out_filename));
header('Content-Disposition: attachment; filename="' . $pdf_filename . '"');

@readfile($out_filename);

When the php loads and I get the dialog box to download the pdf, the onload event on the iframe does NOT fire. Is there any way to have the front end detect when the php file has completed and the pdf file is ready?

1 Answers

You could try setting the content disposition to inline.
Then use the ifr1's onload to begin the download.
I tested this script like this.

<!DOCTYPE html>
<html lang="en">
<head><title>Download PDF</title>
<style></style></head><body>
<iframe id='ifr1' src="./myfile.php" height="200" width="300" onload="dlpdf()"></iframe>
<script>
function dlpdf(){
  document.getElementById('ifr1').contentWindow.download();
}
</script>
</body></html>

And this is myfile.php

<?php
ob_start();
ob_clean();

  $file = "./myfile.pdf";

  header('HTTP/1.1 200 OK');
  header('Connection: Keep-Alive');
  header('Cache-Control: private, max-age=0');
  header('Content-Length: ' . filesize($file));
  header('Content-type: application/pdf');
  header('Content-Disposition: inline; filename="' . $file . '"');
  header('Accept-Ranges: bytes');
  header('Keep-Alive: timeout=5, max=100');
  readfile($file);
  ob_end_flush();
  
?> 
Related