【问题标题】:Unable to print the pdf loaded in iframe无法打印 iframe 中加载的 pdf
【发布时间】:2014-10-10 20:39:21
【问题描述】:

我有一个带有按钮和 IFRAME 的页面。在 IFRAME 中,我正在动态加载来自不同域的 PDF 文件。

当我尝试使用按钮操作打印文件时,出现以下错误。

Uncaught SecurityError: Blocked a frame with origin "http://localhost:8080" from accessing a frame with origin "http://www.cplusplus.com". Protocols, domains, and ports must match.

如果我从本地系统加载 pdf 文件,我将打印它。

我使用以下代码打印 iframe Pdf

var iframe = document.querySelector("#unofficialtranscript");
iframe.focus();
iframe.contentWindow.print();

知道如何打印加载到另一个域上的 iframe 中的文件。

【问题讨论】:

    标签: javascript iframe


    【解决方案1】:

    我认为您需要查看same origin policy。只有在接受策略时,Javascript 才会调用窗口或 iframe。

    您可能需要改用Postmessage API

    请看here

    【讨论】:

    • 我看到很多示例使用 Postmessage api 从主页发送消息到 IFRAME,但我的情况不同,需要打印文件。我不知道该怎么做
    【解决方案2】:

    如果父 DOM 和子 DOM(即 iframe)都来自同一个域,那么它将正常工作。

    如果没有,则使用 Porthole 之类的库进行不同域之间的交叉通信。

    演示站点:http://sandbox.ternarylabs.com/porthole/

    注意:您应该可以访问代码中使用的两个域。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多