我决定用 Javascript 发布答案,因为它实际上并不简单:(
我在问题中写的内容不能跨浏览器工作(实际上是 Firefox,这次不是 IE!)
问题是,在 Firefox 中,print()
实际上是非阻塞的,所以在我上面的例子中,新open()
窗口会在 Firefox 打印之前关闭!
因此,您可以让窗口保持打开状态,也可以尝试使用隐藏框架;
function printUrl(url) {
var frame = document.createElement('iframe');
frame.setAttribute('src', url);
//must be in the DOM to work in Firefox/IE
document.body.appendChild(frame);
//since it's in the DOM we need to hide it (lest we ruin our page layout)
//can't use 'display:none' or 'visibility:hidden' because you can't get focus (needed for IE)
//'z-index:-1' & 'opacity:0' wont help if there is no background in the elements above it and someone clicks through to it
frame.style.position = 'absolute';
frame.style.left = '-9999px';
//when it is loaded, print it
function printFrame() {
//have to get focus in IE
frame.contentWindow.focus();
//print!
frame.contentWindow.print();
/* cant remove the element because print() is non-blocking in FF
* (I.e. it would remove the frame before it was printed!)
//cleanup
//document.body.removeChild(frame);*/
};
//if it was cached, it may already be done (onload wont fire, IE8)
if (frame.contentWindow && frame.contentDocument.readyState == 'complete')
printFrame();
else {
if (frame.addEventListener)
//W3C
frame.addEventListener('load', printFrame, false);
else
//IE<9
frame.attachEvent('onload', printFrame);
}
}
经测试可在 FF、Chrome 和 IE>7 中工作
请注意,与简单open()
(如果工作)一样,这将无法跨站点工作。您不能window
在弹出窗口或框架中访问不同域中页面的方法。