Search code examples
javascriptevent-handlingmicrosoft-edge

afterprint not detected while hidden printing in an iFrame


I've spent nearly 2 days googling and trying lots of example (even here in StackOverflow), and I don't find any way to fire the event "afterprint". It seems dead. I've found some fiddle, where it works, and when I try to reproduce on my system, it doesn't. I am not sure what I'm doing wrong.

Here is the code I want to use:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>PDF Printing</title>
  </head>
  <body>
        <button id="myButton2" onClick="printPage('http://localhost/~user/testPDF.pdf')">Print Me 2</button><br>

        <script type="text/javascript">
        function closePrint () {
                console.log("Ciao");
                document.body.removeChild(this.__container__);
        }

        function printPage (sURL) {
                var myButton = document.getElementById("myButton2");
                myButton.disabled=true;

                var printFrame = document.createElement("iframe");
                printFrame.id = "printPDF2";
                printFrame.style.display = 'none';
                printFrame.src = sURL;
                printFrame.onload = function() {
                  printFrame.contentWindow.addEventListener('afterprint', function(evt) {
                    console.log("yellow");
                    document.body.removeChild(iframe)
                  });
                  this.contentWindow.__container__ = this;
                  this.contentWindow.onbeforeunload = closePrint;
                  this.contentWindow.onafterprint = closePrint;
                  this.contentWindow.focus(); // Required for IE
                  this.contentWindow.print();
                }
                document.body.appendChild(printFrame);
        }
</script>
  </body>
</html>

I've tried also with the MediaDetect. And it doesn't work... (I used these links for inspiration: https://jsfiddle.net/5qbc1pzj/ and https://jsfiddle.net/anhhnt/nj851e52/) the JS console is empty... I get no "Ciao" or "yellow"...

I'm using a simple Apache server, and using the latest IE Edge (103.0.1264.62).

I am out of idea, could someone give me an idea, where to look at?

Thank you in advance.

Kind regards, Alessandro


Solution

  • It doesn't work because detecting the print events only work for HTML-documents. The MIME type for PDF windows is application/pdf so it doesn't work. The events that are available on the window are not available to the <embed> like tags, as they are handled by the browser's default application for the type. Although the event occurs here, it is not bubbled back to the window. For more information, you can refer to this answer.

    The only solution to this seems to create your own PDF viewer. For example, you can use PDF.js.