【问题标题】:Remove iframe after printing打印后删除 iframe
【发布时间】:2016-05-12 12:04:19
【问题描述】:

我是 HTML 和 Javascript 的新手。我正在尝试编写一个 Javascript 函数来打印(隐藏的)iframe 的内容,以便在不打开文档的情况下(看似向用户)打印文档。

我的函数基于我在这里找到的示例:https://developer.mozilla.org/en-US/docs/Printing#Print_an_external_page_without_opening_it

打印内容工作正常,但问题是打印完成后从文档中删除 iframe。这就是我的代码现在的样子。

function closePrint () {
            var element = document.getElementById("printFrame");
            element.parentNode.removeChild(element);
        }

        function setPrint () {
            this.contentWindow.__container__ = this;
            this.contentWindow.onbeforeunload = setTimeout(closePrint, 100);
            this.contentWindow.onafterprint = setTimeout(closePrint, 100);

            this.contentWindow.focus(); // Required for IE
            this.contentWindow.print();

        }

        function printPage (sURL) {
            var oHiddFrame = document.createElement("iframe");
            oHiddFrame.onload = setPrint;
            oHiddFrame.width = 0;
            oHiddFrame.height = 0;
            oHiddFrame.style.position = "fixed";
            oHiddFrame.style.right = "0";
            oHiddFrame.style.bottom = "0";
            oHiddFrame.id = "printFrame";
            oHiddFrame.src = sURL;
            document.body.appendChild(oHiddFrame);
        }

我在示例中更改了两行

            this.contentWindow.onbeforeunload = closePrint;
            this.contentWindow.onafterprint = closePrint;

            this.contentWindow.onbeforeunload = setTimeout(closePrint, 100);
            this.contentWindow.onafterprint = setTimeout(closePrint, 100);

因为它没有在没有超时的情况下删除 iframe。 这在 IE11 和 Chrome 中都可以正常工作,但在 IE 兼容模式(我认为它模拟 IE7)中,当我尝试使用 setTimeout 时,它会给我一个错误“未实现”。

所以我的问题是,当我打印内容时,是否有另一种方法可以在超时后运行 closePrint 函数,或者是否有其他方法可以从文档中删除 iframe?任何帮助表示赞赏。

【问题讨论】:

  • 尝试删除带有onbeforeunloadonafterprint 的行。只需在this.contentWindow.print(); 之后调用closePrint()。这将起作用,因为打印功能正在阻止下一个 js 执行。
  • @BobSponge 我尝试了你的建议,但它不起作用。在 Chrome 中,它只是创建 iframe,然后在不打印的情况下关闭它。在 IE 兼容性中,它会打印但不会关闭 iframe。但在普通的 IE11 中它确实可以工作。
  • 它对我有用,至少在 Chrome 中是这样。您是否尝试打印具有相同来源(协议、域和端口)的页面?
  • 是的,http,localhost 在 8080。奇怪的东西。我会尝试更多。
  • 好吧,看来您的解决方案实际上可以在 IE11 中使用和不使用兼容模式,DOM 树只需要几秒钟就可以在调试器中重新加载/更新。所以我想我会检查使用的是哪个浏览器并相应地运行代码。

标签: javascript internet-explorer iframe printing onbeforeunload


【解决方案1】:

打印后,将 iframe 留在document.body。当您需要添加下一个 iframe 时,首先检查它的存在 ~ 如果存在,然后将其删除(前两行)。

myfunction() {
  const iframe = document.querySelector('iframe');
  if (iframe) iframe.parentNode.removeChild(iframe);
  const i = document.createElement('iframe');
  i.style.display = 'none';
  i.src = this.study.DocumentUrl;
  document.body.appendChild(i);
  document.querySelector('iframe').contentWindow.focus();
  document.querySelector('iframe').contentWindow.print();
}

【讨论】:

    猜你喜欢
    • 2013-01-18
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2011-05-05
    • 2020-01-15
    相关资源
    最近更新 更多