Trigger JavaScript on Print Event

Execute JavaScript actions seamlessly during printing with this easy-to-implement code snippet.

Usage

Integrating JavaScript functionalities upon triggering a print event can enhance user experience and customization. Below is a concise guide to implementing this feature using simple code snippets.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Your Web Page</title>
  <!-- Include your other head elements here -->
</head>
<body>
  <!-- Your webpage content goes here -->
  <!-- Add JavaScript file or inline script if required -->
</body>
</html>

JavaScript Code

JavaScript
<script>
  // Detect print event
  window.onbeforeprint = function() {
    // Your custom JavaScript code to execute before printing
    console.log("Executing JavaScript before print event");
  };

  // Optionally, detect after print event
  window.onafterprint = function() {
    // Your custom JavaScript code to execute after printing
    console.log("Executing JavaScript after print event");
  };
</script>

This code binds functions to the onbeforeprint and onafterprint events, allowing you to execute specific actions before and after the print event, respectively.

Important Note: For anyone discovering this snippet through a search engine, it’s crucial to note that the window.onbeforeprint and window.onafterprint events, while powerful, have limited support. The behavior of these events can vary, and in some cases, both events may fire before the print dialog, or script execution might be halted during the dialog.

We recommend the use of a @media print CSS at-rule, which is generally preferred for modifying content before printing. However, there might be scenarios where utilizing the window.onbeforeprint and window.onafterprint events becomes necessary.

For example

CSS
@media print
{    
    .no-print, .no-print *
    {
        display: none !important;
    }
}

Testing

Test the implementation by printing the document. Open the browser’s print dialog (usually accessible through Ctrl + P or Cmd + P), and observe the console logs to ensure the JavaScript executes as intended.

FAQs

Can I use this method to customize the printed content?

Yes, you can modify the document styles or content within the onbeforeprint event to tailor the printed output.

Are there any browser compatibility issues?

This method is widely supported across modern browsers, but it’s advisable to test and ensure compatibility for specific use cases.

Can I prevent the default print behavior using this approach?

While it’s not the primary purpose of this snippet, you can prevent the default print behavior by returning false within the onbeforeprint event.

References

Leave a Reply