I have an iframe that shows documents using an embedded viewer on my website. When I click inside the iframe and press ctrl+p, it works fine and prints the document correctly. But there’s no visible print button in the viewer interface.
I tried to create a button on my main page that would focus on the iframe and call the print() function. However, when I do this, the print dialog opens for the main page instead of the iframe content.
Is there a way to make the iframe print its content when triggered from a button on the parent page? I want to give users an easy way to print without knowing the keyboard shortcut.
yea, i get this all the time too. if ur iframe’s on the same domain, just use iframe.contentWindow.print(). but watch out—most document viewers block that stuff for security. maybe try adding a message listener in the iframe that triggers print when the parent sends a msg. postMessage API is great for that!
Had this exact problem building a document management system last year. Most embedded document viewers block external print triggers for security - even contentWindow.print() won’t work. Here’s what fixed it for me: I added a small overlay div positioned over the iframe with a custom print button. When clicked, it first tries contentWindow.print(), but if that fails, it opens the document URL in a new tab with print parameters. Most document viewers support URL params like ?print=true or ?action=print that auto-trigger the print dialog when the page loads. Users get a consistent print experience no matter what restrictions the viewer has.
Cross-origin restrictions make this tricky since iframe content runs in a different security context. I’ve encountered this issue before; the most reliable fix is to access the iframe’s contentWindow directly. Try using document.getElementById('your-iframe-id').contentWindow.print() instead of focusing first. This specifically targets the iframe’s print function rather than the parent page’s. However, this works only if the iframe content is from the same domain. If it’s cross-origin, you’ll need postMessage communication between the parent and the iframe, necessitating modifications to the iframe content to listen for print commands. For third-party document viewers, refer to their API documentation for programmatic printing options.