问题描述
使用 JavaScript,您可以通过使用 window.print()
以编程方式触发打印对话框。 .但是,只要 iframe
加载到带有 的页面中PDF 作为 src
并且您刷新页面,当单击应该执行 window.print()
的按钮时,将不再显示打印对话框功能。
该问题在 MS Edge 和 Firefox 中都不会发生...只有 的最新版本谷歌浏览器 (77.0.3865.120) 似乎受到了影响。这是 Chrome 错误吗?
重现错误的步骤
<!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>
结论
window.print()
只要你有 iframe
,对话框就会变得毫无用处。在您的页面上使用 PDF 作为 src
属性。
最佳答案
According to the Chromium team ,此错误将在 Chrome 80 中修复(由于 to be released Feb 2, 2020 )。
对用户的临时修复可以是禁用跨进程框架中的 MimeHandlerView: chrome://flags/#mime-handler-view-in-cross-process-frame
或者,正如提问者所说,重新打开选项卡/窗口。
对于开发人员,遗憾的是,在那之前我还没有找到解决此问题的好方法。 window.onbeforeprint(event)
没有被调用,并且 window.print()
返回 undefined
不管。
关于javascript - 在页面重新加载时, "window.print()"不会在 Google Chrome 77.0.3865.120 中加载打印对话框。当 IFRAME 与作为 SRC 的 PDF 一起使用时会发生这种情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58345341/