How do I print an IFrame from javascript


You can print the content of an IFrame using JavaScript by calling the print() method on the contentWindow object of the IFrame. Here’s an example:


<iframe id="my-iframe" src=""></iframe>
<button onclick="printIframe()">Print</button>


function printIframe() {
  const iframe = document.getElementById('my-iframe');
  const contentWindow = iframe.contentWindow;

In this example, we first define an IFrame with the id “my-iframe” and a button that calls the printIframe() function when clicked.

The printIframe() function uses the document.getElementById() method to get a reference to the IFrame element, and then accesses its contentWindow property to get a reference to the window object that contains the content of the IFrame. Finally, it calls the print() method on the contentWindow object to print the content.

Note that the print() method will only work if the content of the IFrame is from the same origin as the page that contains the IFrame. If the IFrame contains content from a different origin, the browser’s security policies will prevent the content from being printed.