打印后删除iframe

时间:2016-02-03 10:33:09

标签: javascript internet-explorer iframe printing onbeforeunload

我是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的其他方法?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

打印后,将iframe留在jsonString: {"USA":{"firstName":"Tom","lastName":"Sawyer"},"UK":{"firstName":"Jane","lastName":"Doe"}} deserialized: {USA=ContactPerson(firstName=Tom, lastName=Sawyer), UK=ContactPerson(firstName=Jane, lastName=Doe)} 上。当您需要添加下一个document.body时,请先检查其存在〜如果存在,则将其删除(前两行)。

iframe
相关问题