JavaScript

What is the Window Print() Method in JavaScript?

The window print() method is used to print the visible contents of the current window, for example, a web page text or image by displaying the Print Dialog Box which allows the user to choose from a variety of printing options, and the Print Dialog Box is only opened when the print() code is executed.

Syntax:

window.print();

This will open a Print Dialog Box which will print the visible content of the current window as discussed earlier.

It should be noted that the window.print() method does not take or contain any parameters and also doesn’t return anything.

Browsers Support

The window.print() method is supported by many browsers and some of them are as follows:

Browser Chrome Internet Explorer Firefox Safari Opera
Support Yes Yes Yes Yes Yes

Example

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<body>
   <h2>Window Print Example!</h2>
   <button class="btn">Click Me</button>
   <script src="code.js"></script>
</body>
</html>

In the above HTML code, we defined h2 tags and then created a button that says Click me. After this, we put the script tag which is referencing code.js which will make JavaScript connect to HTML.

JavaScript:

const btn= document.querySelector(".btn");
btn.addEventListener('click', function(){
   window.print();
});

In the above code, we are referencing the button in the HTML by using the class anime associated with it. After this, we added an event listener of click which will continuously listen for a click event and whenever someone clicks on the Click Me button, the function within the event listener will run.

When we first execute the above code of HTML and JavaScript we will see the following on our browser:

When we click on the Click Me button, the Print Dialog box will open:

We can see the content of our webpage on the left-hand side of the Print dialog box and when we click on the print button it will print or save the current viewscreen in a file.

Conclusion

We learned everything about the window.print() method and answered the question of what the window.print() method is in JavaScript along with an example in this post. To recap, the window.print() method prints the current windows visible content which can be anything like image, text, or any advertisement. We also saw that whenever the window.print() method is executed the print dialog box opens where a user can choose their preferred options to print the document.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.