w3resource

JavaScript: Print the contents of the current window

JavaScript Basic: Exercise-2 with Solution

Write a JavaScript program to print the current window contents.

Sample Solution:

JavaScript Code:

// Define a function named print_current_page
function print_current_page() {
    // Call the window.print() method to initiate the printing of the current page
    window.print();
} 

Output:

Click the button to print the current page.

Live Demo:

See the Pen JavaScript current day and time - basic-ex-2 by w3resource (@w3resource) on CodePen.


Explanation:

window.print(): The window object represents a window containing a DOM document; the document property points to the DOM document loaded in that window, window.print() is used to open the Print Dialog to print the current document.

ES6 Version:

function print_current_page()
{
window.print();
}

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to display the current day and time in a specific format.
Next: JavaScript program to get the current date.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.