下面是我在 Windows XP 上的 IE 8 中运行良好的 javascript 代码。
<script type="text/javascript">
function printFrame(frameId) {
var iframe = $('#'+frameId)[0];
iframe.contentWindow.focus();
iframe.contentWindow.print();
}
</script
调用上述函数,然后在父页面中单击“打印框架”按钮。
<iframe id="testFrame" src="" name="testFrame"> </iframe>
<input type="button" onclick="printFrame('testFrame')" value="Print Frame"/>
最近,我将我的机器升级到 Windows 7,并将 IE 8 升级到 IE 11。
现在这个相同的函数没有给出打印 iframe 内容的预期结果。 我在 chrome v34、firefox 30 中对此进行了测试。这似乎在 IE 11 中除外。
在研究中,我发现动态设置iframe src时,iframe.contentWindow不会返回异常的iframe窗口对象。
我尝试在 iframe 的 jsp 中使用 window.print()。如果 src 没有动态更改,这似乎有效。但是我需要根据父页面中另一个下拉框中的选择更改 iframe 的内容以动态设置。
例如,在 IE 11 中检查以下链接。
http://plungjan.name/SO/testprintiframe.html
链接第一次打印 iframe 上的内容。然后,单击按钮。这导致将父窗口而不是 iframe 内容发送到打印机。
然后我尝试了另一种方法。 在 iframe 内容 jsp 中编写以下代码并尝试从父页面访问它。我无法访问该方法本身。 “iframe jsp 中的脚本代码”
<script type="text/javascript">
function printFrame() {
window.print();
}
</script
“父jsp中的脚本代码”
尝试 1:
<script type="text/javascript">
function printMyFrame(frameId) {
var iframe = $('#'+frameId)[0];
$(iframe).contents().printFrame();
}
</script
尝试 2:
<script type="text/javascript">
function printMyFrame(frameId) {
setTimeout(function() {
window.frames[frameId].contentWindow.printFrame();
}, 200);
}
</script>
我搜索并实现了几乎所有在谷歌搜索中找到的方法来访问 iframe 窗口而不是父窗口。但是无法使用 IE 11 打印 iframe 内容。
请指导我如何在 IE 11 中打印 iframe 内容。
最佳答案
最近遇到了类似的问题,发现需要这个方法
var target = document.getElementById('print-container');
try {
target.contentWindow.document.execCommand('print', false, null);
} catch(e) {
target.contentWindow.print();
}
});
关于javascript - 无法从 IE 11 中的父页面打印 iframe 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24673024/