Execute a script before the document is printed in HTML?


The task we are going to perform in this article is execute a script before the document is printed in HTML.

When a page is about to be printed, the HTML onbeforeprint attribute is used. And before the print dialogue box appears, the alert message is displayed. Together with the onafterprint attribute, the onbeforeprint attribute is utilised. This is a part of event attribute.

Let’s dive into the following examples to understand more about to execute a script before the document is printed in HTML.

Example 1

In the following examples we are using HTML onbeforeprint attribute.

<!DOCTYPE html>
<html>
   <body onbeforeprint="mytutorial()">
   <h1>MS DHONI</h1>
   <h2>Finishes off in his Style.</h2>
   <script>
      function mytutorial() {
         alert("Sure To Print!");
      }
   </script>
</body>
</html>

When the script gets executed, it will generate an output displaying the text used in the script on the webpage.

When the user tries to print the webpage, the event gets triggered and displays an alert "sure to print" on the webpage.

Example 2

Here is the another example for implementing onbeforeprint attribute.

<!DOCTYPE html>
<html>
   <body onbeforeprint = "display()">
   <h1>TUTORIALSPOINT</h1>
   <script>
      function display() {
         alert("The document will now print.");
      }
   </script>
</body>
</html>

On running the above script, the output window pops up and displays the text "tutorialspoint" on the webpage.

If the user tries to print the webpage, the event gets triggered and displays an alert on the webpage.

Updated on: 16-Dec-2022

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements