- window . print ( )
- Как пишется
- Как понять
- How to print in JavaScript — with code examples
- Print with console.log() method
- Print with document.write() method
- Print using window.alert() method
- Print by changing the innerHTML property of your element
- Learn JavaScript for Beginners 🔥
- About
- Search
- Tags
- How to Print a Webpage or Part of It in JavaScript Like a Pro
- How to Print Entire HTML Web Page Using JavaScript
- How to Print a Specific Part of a Web Page in JavaScript
- Conclusion
window . print ( )
Вызов метода print ( ) объекта window открывает стандартный диалог печати текущей страницы.
Как пишется
Скопировать ссылку «Как пишется» Скопировано
window.print()
window.print()
Как понять
Скопировать ссылку «Как понять» Скопировано
При создании приложения мы можем предложить пользователю распечатать текущую страницу. Например, если показываем ему номер оформленного заказа, подтверждение бронирования и так далее.
Для этого достаточно написать несколько строк кода. Например, открывать системный диалог печати при нажатии на кнопку:
const printButton = document.getElementById('print-button') printButton.addEventListener('click', function() window.print()>)
const printButton = document.getElementById('print-button') printButton.addEventListener('click', function() window.print() >)
Такой код делает то же самое, что и системное меню File → Print.
По умолчанию страница печатается в том виде, какой её видно на экране — цветная, с шапкой, футером, меню. Печатную версию сайта можно настроить с помощью CSS-директивы @media print и скрыть ненужные блоки.
How to print in JavaScript — with code examples
Posted on Apr 25, 2022
Depending on what you want to print and where you run JavaScript code, there are several ways to print in JavaScript.
When you want to print the current webpage of your browser, you can use the window.print() method.
The window.print() method will print the content of the currently active tab in your browser.
You can run the method from the browser console to print the webpage with your printer.
- Print to the console using console.log()
- Print to the browser interface using document.write()
- Print to the alert box using window.alert() method
- Print to the HTML tag by changing innerHTML property value
Let’s see how to do each one of these methods next.
Print with console.log() method
The console.log() method allows you to print JavaScript data and values to the console.
This is useful when you want to check the value of variables you have in your JavaScript code as shown below:
The console.log() method instructs the JavaScript console to log the value passed as its parameter.
The console is available both on the browser and the Node.js server.
Print with document.write() method
The document.write() method is used to write data to the tag of your HTML document.
This method will erase all data stored inside the tag of your webpage.
For example, suppose you have the following HTML document rendered in your browser:
When you run a document.write() command from the browser’s console, the HTML document above will be overwritten.
Running the following command:
Will produce the following output:
As you can see, all attributes and elements previously written in the document have been erased.
The document object model is not available in the Node.js server, so you can only use this method from the browser.
Print using window.alert() method
The window.alert() method is used to create an alert box that’s available in the browser where you run the code.
For example, running the code below:
Will produce the following output:
Using window.alert() method, you can check on your JavaScript variables and values with the browser’s alert box.
Print by changing the innerHTML property of your element
You can print to a specific HTML element available on your webpage by changing the innerHTML property of that element.
For example, suppose you have the following HTML document:
The HTML document will have the following changes:
Once you get the element, change the innerHTML property value, and that change will be reflected on your browser page.
Now you’ve learned how to print data and values in JavaScript. Good job! 👍
Learn JavaScript for Beginners 🔥
Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.
A practical and fun way to learn JavaScript and build an application using Node.js.
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
How to Print a Webpage or Part of It in JavaScript Like a Pro
JavaScript provides a convenient way to generate a physical copy of a document. You can print your web page just by calling a method globally available in the window object.
There is also a way to print a specific part of your webpage. You can extract the necessary portion and get the print of it.
In this tutorial, we'll explore various techniques for printing a webpage or specific sections using JavaScript. You can do it by clicking on a button.
But that's not all. We'll also learn how to customize the print output with CSS styling to ensure a professional look and feel.
Printing a web page or a specific part of a web page can be accomplished by calling the window.print() method in JavaScript. This method opens a print dialog box where users can select different options to generate a printed copy of the content easily.
How to Print Entire HTML Web Page Using JavaScript
Printing an entire webpage using JavaScript is a straightforward process. All you need to do is call the print() method on the window object.
This method is available in all modern browsers and is specifically designed to print the current window's contents.
I have a button on my page. It will print the page whenever I click this button. For that, you need to set up a click event listener on this HTML button element.
const btn = document.getElementById('btn') btn.addEventListener('click', () => < window.print() // Print the entire webpage >)
Here, I am listening to the click event on this button. If you click this button, it will execute the callback function which calls the window.print() method.
It will open a print dialog box, allowing you to select appropriate options for printing the current document.
How to Print a Specific Part of a Web Page in JavaScript
So far you have seen the technique to print a full page. Often we want to print part of a page using JavaScript. You can get it using this window.print() method.
Printing a specific section of a page is a little complex. But don't worry I will explain each step in detail so that you understand the process.
Step 1: I am selecting the button element that will trigger the click event. I am also selecting the section that I want to print and store in the sectionToPrint variable.
const btn = document.getElementById('btn') const sectionToPrint = document.getElementById('section-to-print') btn.addEventListener('click', () => < // Select and print a section of a webpage here >
Step 2: Inside the event callback function, open a new browser window by calling the window.open() method. I am not specifying any URL, so it will open a blank page.
The second parameter of this method sets the name of the new window to "Print Window". The printWindow variable now holds a reference to this new window.
// Create a new window with only the section to print const printWindow = window.open('', 'Print Window')
Step 3: As you already know, it will open a black window. Therefore, you need to write an HTML markup for this printWindow window using the printWindow.document.write() method.
First, add different HTML tags like html , head , title , body etc. You also have to link an external CSS stylesheet using the link tag. Because this window won't have any style by default.
printWindow.document.write('') // Link to the CSS stylesheet printWindow.document.write('') printWindow.document.write('')
Step 4: Add the section you want to print to the body of this new window. You can get the HTML content of that section from the innerHTML property.
I will also add a button element with an ID print-btn to this window. Because I will trigger a click event to print my printWindow window by clicking this button.
// Add the section you want to print printWindow.document.write(sectionToPrint.innerHTML) // Add a button to the new window and listen for the click event printWindow.document.write('
Step 5: I am selecting this button using its ID and listen to the click event. When I click this button, the event callback function will execute.
The function removes that button using the remove() method. Because I don't want to keep it in my print. Then it will call the print() method on the printWindow object.
This method will open the print dialog box to select options and print it. Finally, you will close this printWindow window by calling printWindow.close() method.
const printBtn = printWindow.document.getElementById('print-btn') printBtn.addEventListener('click', () => < // Remove the print button printBtn.remove() // Print the new window printWindow.print() printWindow.close() >)
By following these 5 steps, you can print any section of your webpage. You just have to open a new window with that section and add necessary elements like buttons, CSS styles, etc.
Here is the complete code:
const btn = document.getElementById('btn') const sectionToPrint = document.getElementById('section-to-print') btn.addEventListener('click', () => < // Create a new window with only the section to print var printWindow = window.open('', 'Print Window') printWindow.document.write('') // Link to the CSS stylesheet printWindow.document.write('') printWindow.document.write('') // Add the section you want to print printWindow.document.write(sectionToPrint.innerHTML) // Add a button to the new window and listen for the click event printWindow.document.write( '
Conclusion
Printing web pages or sections of them using JavaScript can be a useful feature for a variety of applications. You can enhance the user experience and provide your users the ability to print your content.
Using the window.print() method, you can quickly and easily print the entire web page. To print a specific section of a web page, create a new window with that desired content.
This also allows you to customize the styles, remove unnecessary elements, and ensure that the content is being printed exactly as you want.