【问题标题】:How do print specific content inside the iframe如何在 iframe 中打印特定内容
【发布时间】:2013-08-28 11:16:42
【问题描述】:
<script type="text/javascript">
function printDoc() {
   document.getElementById("frame_singleCheque").contentWindow.print();
}
</script>

<iframe  style ="height:400px; width: 750px; overflow:scroll;"  id="frame_singleCheque" src="http://www.w3schools.com"></iframe>
<input type="button" id = "btnCPrint" value = "Print" onclick="javascript:printDoc()" />

错误

[16:41:44.054] Error: Permission denied to access property 'print' @ http://localhost/pdf/print.php:3

我已经验证了许多堆栈建议线程用于打印 iframe 内容。但对我来说,这些都行不通。

上面的代码只出现在我的 print.php 文件中。我想打印 iframe 内容。

我还想知道,如何打印 iframe 中存在的特定 div。此 iframe 中的示例“class= 'example_code notranslate'”。

【问题讨论】:

  • 首先是focus() windowiframe,然后是print()
  • 您可以访问 iframe 的内容吗?是你的页面吗?
  • 您不能将内容注入/获取来自不同域的页面/从它违反安全沙箱的页面。
  • 从 HTML5 开始,您可以更好地控制 iFrame。通过使用 sandboxseamless 属性,您可以将 iframe 进一步集成到您的网页中 - w3ctutorial.com/html5-tags/tag-iframe

标签: javascript jquery iframe


【解决方案1】:

您可以通过将跨域 iframe 嵌套在本地托管的 iframe 中来完美打印跨域 iframe 页面。 “代理 iframe”。

这样,父 javascript 可以毫无问题地打印代理 iframe,因为它是本地的,这将传递地打印它来自另一个域的内部 iframe。

此技术有效,并已由我自己验证。

在您的容器页面中,像这样托管 iframe

 <iframe id="printf" name="printf" class="A4" src="/SomeController/IFrameProxy?url=TARGETURL"></iframe>

代理 iframe 应该看起来像这样

        @model string
        <html>
            <head>
                <title>IFrame Proxy</title>
                <style>
                    html, body, iframe {
                        height: 100%;
                        width: 100%;
                        margin: 0;
                        padding: 0;
                        border-style: none;
                    }
                </style>

            </head>
            <body>
                <iframe src="@Model" seamless></iframe>
            </body>
        </html>

打印 iframe(在容器页面上定义)的 javascript 应该如下所示:

        function printFrame() {
            var frm = document.getElementById("printf").contentWindow;
            frm.focus();// focus on contentWindow is needed on some ie versions
            frm.print();
        }

【讨论】:

【解决方案2】:

看起来您在这里遇到了一个非常标准的跨域 iframe 问题 - 即浏览器的设计使您无法做到这一点。我可以建议很多软糖,但在很大程度上,iframe 是解决这个问题的错误解决方案。

基本上,您最好的选择是抓取页面 - 发出 http 请求并解析出您想要的内容。然后,您可以将其作为您自己页面的 DOM 的一部分与之交互。

【讨论】:

  • 投了反对票,因为您可以使用我的回答中显示的技术打印跨域 iframe。
【解决方案3】:

【讨论】:

  • 投了反对票,因为链接不包含跨域 iframe 打印的有用参考。
猜你喜欢
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2021-05-21
  • 2012-03-25
  • 1970-01-01
  • 2010-12-11
相关资源
最近更新 更多