[英]Unable to print an iframe on IE using JavaScript, prints parent page instead
[英]Unable to print iframe content from parent page in IE 11
以下是在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();
}
});
这对我有用,
这适用于ie,chrome和firefox
var result = contentWindow.document.execCommand('print', false, null);
if (!result)
contentWindow.print();
这基本上是jsFiddle中上述答案(Nayas Subramanian)的重复 - 但安全性不允许它在stackoverflow中100%工作...
$('#print').click(function () { var contentWindow = document.getElementById("frameContent").contentWindow; var result = contentWindow.document.execCommand('print', false, null); if(!result) contentWindow.print(); });
iframe { width:100%; height:100%; border: none; } #print { position:absolute; left:20px; top: 20px; font-size: 20px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <iframe id="frameContent" name="frameContent" src="https://stackoverflow.com/questions/24673024/unable-to-print-iframe-content-from-parent-page-in-ie-11#"></iframe> <button id="print">Print</button>
看起来iframe无法通过IE11上的javascript打印。 我尝试了几种方法并且没有成功。 这个链接也是如此。
以下代码在IE 10和IE 11中都适用于我
var browserName = navigator.userAgent.toLowerCase();
if ( browserName.indexOf("msie") != -1) {
window.document.getElementById('pdfFrame').print();
} else if(browserName.indexOf("trident") != -1) { //IE 11
window.document.getElementById('pdfFrame').contentWindow.document.execCommand('print', false, null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.