''afterprint' event not firing on first page load in Chrome

I have a page where I need to hide some elements when the print dialog is opened via a button on the page. The basic functionality of the code is pasted below. Chrome is the required browser for this project and no other browsers are supported or allowed.

The issue is that the 'afterprint' event is not firing on the first load of the page. If I refresh the page, the code functions as expected. The steps to reproduce are:

  1. Navigate to page in Chrome
  2. Click print button
  3. Click 'Cancel' in print dialog and 'afterprint' event does not fire.

The strange thing is that if I then refresh the page, the code works as expected. Another strange thing is that if I just double click the html file and it opens in chrome, then code works as expected. This is of course, assuming that chrome is set as the default application used to open html files. I can see the event getting registered in the Global Listeners in the Sources tab of the Chrome dev tools, but it does not fire.

<html>
<body>
<button id="print">Print</button>
<div id="prompt">
    Hide if print dialog is open
</div>
<script>

    document.getElementById('print').addEventListener("click", ev => {
        document.getElementById('prompt').style.display = 'none';
        window.print();
    })
    window.addEventListener('afterprint', ev => {
        console.log('After print')
        document.getElementById('prompt').style.display = 'block';
    })

</script>
</body>
</html>

Any help is appreciated. Thank you.



Solution 1:[1]

I had this exact same issue... when the print button is clicked for the first time, the afterprint event listener did not fire.... But when I clicked the print button for the second time and any consecutive clicks fired the foresaid event listener... I solved this issue as follows

window.addEventListener('beforeprint', beforePrintFunction);
window.addEventListener('afterprint', afterPrintFunction);
window.print();
window.removeEventListener('beforeprint', beforePrintFunction);
window.removeEventListener('afterprint', afterPrintFunction);

This works well for me...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Malin Samaranayake