I’ve got a webpage with documents shown using Google Docs Viewer in an iframe. Users can print by focusing the iframe and using ctrl+p. But there’s no print button visible which might confuse some people.
I tried adding a print link on the main page. It focuses the iframe and calls print(). But the main page catches the command instead of the iframe.
Is there a way to make the embedded viewer print from the parent page? I want to give users an easy way to print without relying on keyboard shortcuts.
Any ideas on how to solve this would be great. Thanks!
I encountered a similar issue with embedded Google Docs Viewer before. My solution involved using the postMessage API to establish communication between the main page and the iframe. I added a custom print button on the parent page that sends a message to the iframe. Inside the iframe, an event listener picks up the signal and then calls the print function. This approach prevented the main page from intercepting the print command. In cases where modifying the iframe is not feasible, opening the document in a new tab and triggering print there can also work effectively.
I’ve dealt with this issue in a project recently. One workaround I found effective was using window.frames to access the iframe’s contentWindow. You can try something like:
document.getElementById(‘printButton’).addEventListener(‘click’, function() {
var iframe = document.getElementById(‘docsViewer’);
iframe.contentWindow.focus();
iframe.contentWindow.print();
});
This method bypasses the parent page’s print function and directly triggers printing in the iframe. Make sure your iframe has a proper ID.
If that doesn’t work, you might need to look into more complex solutions involving postMessage API or opening the document in a new window. But try this simpler approach first - it worked well in my case.