Events
onbeforeprint
The document is about to be printed or displayed in print preview. Window event handler, exposed through the body element in HTML; register on window rather than on an arbitrary element. Event interface: Event. For the described native event: bubbles: no; cancelable: no. Prefer @media print for styling; use this event only for changes CSS cannot express. Example: Open print preview and close it; availability depends on browser/iframe policy. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.
Formal Syntax & Structure
html syntaxhtml
<body onbeforeprint="handleEvent(event)"> window.addEventListener("beforeprint", event => { /* handle event */ });Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| onbeforeprint | JavaScript handler body | Optional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute. |
| event | Event | Event object delivered to the addEventListener callback; event.type is "beforeprint". Inspect target, currentTarget, bubbles and cancelable as appropriate. |
Working Example
Example Snippethtml
<p>Window event monitor</p><button id="print" type="button">Print preview</button><p role="status" id="log">Waiting for beforeprint</p><script> const target = window; const log = document.getElementById("log"); target.addEventListener("beforeprint", event => { log.textContent = String(event.type); }); document.getElementById("print").onclick = () => window.print();</script>