在页面重新加载时,“window.print()”不会在 Google Chrome 77.0.3865.120 中加载打印对话框。当 IFRAME 与 PDF 作为 SRC 一起使用时会发生这种情况

Imr*_*mre 5 javascript debugging iframe google-chrome

问题描述

使用 JavaScript,您可以通过使用window.print(). 但是,一旦以PDFiframe加载到页面中并刷新页面,单击应执行该功能的按钮时将不再显示打印对话框。srcwindow.print()

该问题在 MS Edge 中不会发生,在 Firefox 中也不会发生......似乎只有最新版本的Google Chrome (77.0.3865.120)受到影响。这是 Chrome 的错误吗?

重现错误的步骤

  1. 将下面的代码放在一个 html 文件中,并将其放在网络服务器上(例如 WampServer)
  2. 在 Chrome 中导航到 index.html
  3. 单击 [打开打印对话框] ==> 确定
  4. 单击 [创建 iframe] ==> 确定
  5. 刷新 index.html
  6. 单击 [打开打印对话框] ==> 不行!不会打开打印对话框
  7. 唯一的解决方案是关闭当前的 Chrome 标签并重新打开 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>
Run Code Online (Sandbox Code Playgroud)

结论

window.print()一旦iframe您的页面上有一个以 PDF 作为src属性的对话框,该对话框就变得无用了。

Ask*_* B. 1

据 Chromium 团队称,该错误将在 Chrome 80(预计于 2020 年 2 月 2 日发布)中修复。

用户的临时修复可以是禁用跨进程框架中的 MimeHandlerView:chrome://flags/#mime-handler-view-in-cross-process-frame

或者,正如提问者所说,重新打开选项卡/窗口。

对于开发人员来说,遗憾的是直到那时我还没有找到解决此问题的好方法。window.onbeforeprint(event)不被调用,并且无论如何window.print()都会返回undefined