Problem Description
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?
Steps to reproduce the bug
- Drop the below code in an html file and put it on a webserver (e.g. WampServer)
- Navigate in Chrome to index.html
- Click [Open print dialog] ==> Ok
- Click [Create iframe] ==> Ok
- Refresh index.html
- Click [Open print dialog] ==> Not ok! Will not open the print dialog
- Only solution is closing the current Chrome Tab and reopening index.html
<!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>
Conclusion
The window.print() dialog becomes useless, as soon as you have an iframe on your page with a PDF as the src attribute.




