The HTML onbeforeprint event
The HTML onbeforeprint attribute runs JavaScript right before the page is printed or shown in print preview. For example, <body onbeforeprint="addPrintDate()"> can stamp the date onto the printed copy. Pair it with onafterprint to undo the change afterward.
Overview
The HTML onbeforeprint attribute handles the beforeprint event of the window. That event fires when the document is about to be printed or previewed. As an HTML attribute it belongs on the <body> element, and in a script it is window.onbeforeprint.
Two actions start printing. A call to window.print() fires the event, and the HTML standard says browsers should do the same whenever the user asks for a printed copy or a PDF.
After the load event has finished, the handler runs before print() returns. A print() call made earlier, even from an onload handler, returns at once, and printing waits until then.
Use onbeforeprint to annotate the printed copy, such as adding the time it was printed, and revert that in onafterprint.
The event fires in child frames too, so an iframe receives beforeprint when its parent prints. A frame sandboxed without allow-modals can't start printing itself, though. Its own print() call is ignored, no event fires for it, and Chrome logs Ignored call to 'print()'.
Syntax
<body onbeforeprint="addPrintDate()" onafterprint="removePrintDate()">
Example
<p>Order 1024, three items, ready for pickup.</p>
<p id="stamp"></p>
<button type="button" onclick="window.print()">Print this order</button>
<p>The print preview shows a "Printed" line with the current date and time.</p>
<script>
window.onbeforeprint = function () {
document.getElementById('stamp').textContent = 'Printed ' + new Date().toLocaleString();
};
window.onafterprint = function () {
document.getElementById('stamp').textContent = '';
};
</script>
Best practices
- Reach for an
@media printrule first, and add onbeforeprint only for changes that need script. - Undo every onbeforeprint change in onafterprint, so the page on screen looks the same once the print dialog closes.
- Make the changes synchronously inside the handler. The browser prints the page as it stands right after the event, so a later async update can miss the printout.
- Test with the browser's own Print command as well as
window.print(). Both are meant to fire the same events, so the handler must work even when nobody clicks the page's print button.























