Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onbeforeprint — handling the event before printing

The onbeforeprint attribute on body defines JavaScript code that handles the Window object's beforeprint event. It lets you prepare document content before printing; it does not start printing by itself.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

<body onbeforeprint="JavaScript statements">

onbeforeprint is an event handler attribute on body, not a global attribute. Its value is JavaScript code, not an event name. It handles beforeprint on Window, even though it is written on body.

The browser fires beforeprint during print preparation, before offering the document for printing. The handler can change document content. Setting the attribute does not itself start printing or confirm that a paper copy was produced. If sandboxing blocks the print dialog, neither beforeprint nor afterprint fires.

The corresponding JavaScript property is window.onbeforeprint; assigning it replaces the existing handler in the same slot. window.addEventListener('beforeprint', handler) adds an independent listener.

The example dispatches a synthetic beforeprint to window to check the attribute's handler wiring. The expected text is Ready to print. This test does not open a print dialog or verify the actual printing lifecycle; it requires JavaScript enabled and inline handlers permitted.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>onbeforeprint demo</title>
</head>
<body onbeforeprint="document.getElementById('status').textContent = 'Ready to print';">
  <p id="status">Not prepared</p>
  <script>
    window.dispatchEvent(new Event('beforeprint'));
  </script>
</body>
</html>

Result

Ready to print

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources