How do you print in JavaScript?
Short answer: to print the page, call window.print(). It opens the browser's print dialog, the same one you get with Ctrl + P (Cmd + P on macOS):
<button onclick="window.print()">Print</button>If by "print" you mean showing a value while you code, use console.log(): it writes to the browser console or the terminal.
console.log("Hello"); // Hellowindow.print() opens the print dialog and @media print decides what the printed page looks like.
Every way to print in JavaScript
| What you want | Code | Where it appears |
|---|---|---|
| Print the page or save it as PDF | window.print() | The browser's print dialog |
| Show a value while you debug | console.log(value) | Console (F12) or terminal |
| Show data as a table | console.table(array) | Console |
| Show text on the page | element.textContent = "Hi" | The page |
| Show a pop-up message | alert("Hi") | A browser dialog |
| Change what gets printed | @media print { ... } in CSS | The printed page |
Print the page with window.print()
window.print() takes no arguments and returns nothing. It opens the print dialog for the current page, where the user chooses a printer or Save as PDF:
<button id="print-btn">Print invoice</button>
<script>
document.getElementById("print-btn").addEventListener("click", () => {
window.print();
});
</script>A few things to know:
- JavaScript can't print without the dialog or choose the printer. The user always confirms.
- Call it from a click or another user action, so the dialog doesn't take the user by surprise. Browsers can block dialogs that open again and again.
- The page waits while the dialog is open: code after
window.print()usually runs when the dialog closes.
