With JavaScript, you can programmatically trigger the print dialog, by using window.print()
. However, as soon as an iframe
is loaded into the page with a PDF as the src
and you refresh the page, the print dialog will no longer be shown when clicking on the button that should execute the window.print()
function.
The issue does not happen in MS Edge, neither in Firefox... Only the latest version of Google Chrome (77.0.3865.120) seems to be affected. Is this a Chrome bug?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Chrome bug with window.print()</title>
<script>
function createMyIframe() {
// Create new element
var myIframe = document.createElement('iframe');
// Add src attribute
myIframe.src = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
// Suggestion of Amy does not solve the issue:
// Adding a **sandbox** attribute with a space-separated list of pre-defined values that will REMOVE the particular restrictions.
// Source: https://www.w3schools.com/tags/att_iframe_sandbox.asp
// Adding the following line is no solution. The iframe that is used in this example, will simply no longer open. Both the <head> and <body> tags of the iframe will be empty.
// myIframe.sandbox = 'allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-presentation allow-same-origin allow-scripts allow-top-navigation allow-top-navigation-by-user-activation';
// Add the iframe to the page
document.body.appendChild(myIframe);
}
</script>
</head>
<body>
<h1>Chrome version 77.0.3865.120 (Official build) (64-bits)</h1>
<h2>Bug with JavaScript "window.print()"</h2>
<hr>
<button onclick="window.print();">Open print dialog</button>
<button onclick="createMyIframe()">Create Iframe</button>
</body>
</html>
The window.print()
dialog becomes useless, as soon as you have an iframe
on your page with a PDF as the src
attribute.
According to the Chromium team, this bug will be fixed in Chrome 80 (due to be released Feb 2, 2020).
A temporary fix for users can be to disable the MimeHandlerView in cross-process frame: chrome://flags/#mime-handler-view-in-cross-process-frame
Or, as the asker said, re-open the tab/window.
For developers, I sadly haven't found a good way to fix this until then. window.onbeforeprint(event)
is not called, and window.print()
returns undefined
regardless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With