- JavaScript Output
- Example
- My First Web Page
- Using document.write()
- Example
- My First Web Page
- Example
- My First Web Page
- Using window.alert()
- Example
- My First Web Page
- Example
- My First Web Page
- Using console.log()
- Example
- JavaScript Print
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- window . print ( )
- Как пишется
- Как понять
- Printing
- Using a print style sheet
- Using media queries to improve layout
- Detecting print requests
- Examples
- Open and automatically close a popup window when finished
- Print an external page without opening it
- See also
- Found a content problem with this page?
- How can I pop-up a print dialog box using Javascript?
- 10 Answers 10
JavaScript Output
To access an HTML element, JavaScript can use the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML content:
Example
My First Web Page
My First Paragraph
document.getElementById(«demo»).innerHTML = 5 + 6;
Changing the innerHTML property of an HTML element is a common way to display data in HTML.
Using document.write()
For testing purposes, it is convenient to use document.write() :
Example
My First Web Page
My first paragraph.
Using document.write() after an HTML document is loaded, will delete all existing HTML:
Example
My First Web Page
My first paragraph.
The document.write() method should only be used for testing.
Using window.alert()
You can use an alert box to display data:
Example
My First Web Page
My first paragraph.
You can skip the window keyword.
In JavaScript, the window object is the global scope object. This means that variables, properties, and methods by default belong to the window object. This also means that specifying the window keyword is optional:
Example
My First Web Page
My first paragraph.
Using console.log()
For debugging purposes, you can call the console.log() method in the browser to display data.
You will learn more about debugging in a later chapter.
Example
JavaScript Print
JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser to print the content of the current window.
Example
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
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 и скрыть ненужные блоки.
Printing
There may be times in which your website or application would like to improve the user’s experience when printing content. There are a number of possible scenarios:
- You wish to adjust layout to take advantage of the size and shape of the paper.
- You wish to use different styles to enhance the appearance of your content on paper.
- You wish to use higher resolution images for a better result.
- You want to adjust the user experience of printing, such as presenting a specially-formatted version of your content before printing begins.
There may be other cases in which you want to manage the printing process, but these are some of the most common scenarios. This article provides tips and techniques for helping your web content print better.
Using a print style sheet
Add the following to your tag.
link href="/path/to/print.css" media="print" rel="stylesheet" />
Using media queries to improve layout
You can use the CSS @media at-rule to set a different appearance for your webpage when it is printed on paper and when it is displayed on the screen. The print option sets the styles that will be used when the content is printed.
Add this at the end of your stylesheet. Note that specificity and precedence rules still apply:
@media print /* All your print styles go here */ #header, #footer, #nav display: none !important; > >
Detecting print requests
Browsers send beforeprint and afterprint events to let content determine when printing may have occurred. You can use this to adjust the user interface presented during printing (such as by displaying or hiding user interface elements during the print process).
Examples
Here are some common examples.
Open and automatically close a popup window when finished
If you want to be able to automatically close a popup window (for example, the printer-friendly version of a document) after the user prints its contents, you can use code like this:
doctype html> html lang="en-US"> head> meta charset="utf-8" /> meta name="viewport" content="width=device-width" /> title>JavaScript Window Close Exampletitle> script> function popuponclick() const my_window = window.open( "", "mywindow", "status=1,width=350,height=150", ); my_window.document.write(""); my_window.document.write(''); my_window.document.write( "When you print this window, it will close afterward.
", ); my_window.document.write(""); > script> head> body> p> To try out the code>afterprintcode> event, click the link below to open the window to print. You can also try changing the code to use code>beforeprintcode> to see the difference. p> p>a href="javascript: popuponclick()">Open Popup Windowa>p> body> html>
Print an external page without opening it
If you want to be able to print an external page without opening it, you can utilize a hidden (see: HTMLIFrameElement), automatically removing it after the user prints its contents. The following is a possible example which will print a file named externalPage.html :
doctype html> html lang="en-US"> head> meta charset="utf-8" /> meta name="viewport" content="width=device-width" /> title>MDN Exampletitle> script> function closePrint() document.body.removeChild(this.__container__); > function setPrint() this.contentWindow.__container__ = this; this.contentWindow.onbeforeunload = closePrint; this.contentWindow.onafterprint = closePrint; this.contentWindow.focus(); // Required for IE this.contentWindow.print(); > function printPage(sURL) const hideFrame = document.createElement("iframe"); hideFrame.onload = setPrint; hideFrame.style.position = "fixed"; hideFrame.style.right = "0"; hideFrame.style.bottom = "0"; hideFrame.style.width = "0"; hideFrame.style.height = "0"; hideFrame.style.border = "0"; hideFrame.src = sURL; document.body.appendChild(hideFrame); > script> head> body> p> span onclick="printPage('externalPage.html');" style="cursor:pointer;text-decoration:underline;color:#0000ff;"> Print external page! span> p> body> html>
See also
Found a content problem with this page?
This page was last modified on Jul 7, 2023 by MDN contributors.
How can I pop-up a print dialog box using Javascript?
I have a page with a «Print» link that takes the user to a printer-friendly page. The client wants a print dialog box to appear automatically when the user arrives at the print-friendly page. How can I do this with javascript?
10 Answers 10
unless you mean a custom looking popup.
A bit old, but I like to add . window.print();setTimeout(«window.close()», 100); . This waits enough time for the rest of the page to load, but then hangs until the print button on the print dialogue is pressed, or cancelled, and then neatly shuts the tab down again.
I like this, so that you can add whatever fields you want and print it that way.
function printPage() < var w = window.open(); var headers = $("#headers").html(); var field= $("#field1").html(); var field2= $("#field2").html(); var html = ""; html += ''; html += ' '; html += ""; //check to see if they are null so "undefined" doesnt print on the page.
s optional, just to give space if(headers != null) html += headers + "
"; if(field != null) html += field + "
"; if(field2 != null) html += field2 + "
"; html += ""; w.document.write(html); w.window.print(); w.document.close(); >;
This worked like a charm for me. Needed to allow popups in browser. I’m not sure the «close» ever gets executed, since the tab never goes away.
If you just have a link without a click event handler:
I do this to make sure they remember to print landscape, which is necessary for a lot of pages on a lot of printers.
You can tie it to button or on load of the page.
I know the answer has already been provided. But I just wanted to elaborate with regards to doing this in a Blazor app (razor).
You will need to inject IJSRuntime, in order to perform JSInterop (running javascript functions from C#)
@inject IJSRuntime JSRuntime
Once you have that injected, create a button with a click event that calls a C# method:
(or something more simple if you don’t use MatBlazor)
Something to note, the reason the onclick events are asynchronous is because IJSRuntime awaits it’s calls such as InvokeVoidAsync
PS: If you wanted to message box in asp net core for instance:
await JSRuntime.InvokeAsync("alert", "Hello user, this is the message box");
To have a confirm message box:
bool question = await JSRuntime.InvokeAsync("confirm", "Are you sure you want to do this?"); if(question == true) < //user clicked yes >else < //user clicked no >