1

我想打开一个新窗口/选项卡,在文档中放入一些 HTML,然后打开浏览器打印对话框来打印那个新窗口。我正在使用以下内容来完成此操作:

var w = window.open();
w.document.write(html);
w.document.close();

其中html包含:

...<body onload="window.print()">...</body>...

这一切正常,弹出窗口,并为新页面显示打印对话框,但是,由于某种原因,浏览器在显示打印对话框之前没有等待页面上的所有图像加载。这导致某些图像无法打印。

有很多图像,它们是在服务器端动态生成的(每个大约需要 1 秒才能加载)。如何强制浏览器仅在加载所有图像后打印?

这发生在我已经确认的 Chrome 和 Firefox 中。我很感激任何帮助。

4

2 回答 2

1

Try changing it from the body.onload event to the window.onload event.

w.window.onload = window.print()

Or something like that.

于 2013-07-08T19:35:17.433 回答
1

Try putting your printer call in an onload event for the last image.

<img onload="window.print()" ... />

EDIT:

Full answer by OP as seen below:

I came up with the following script using @chockleyc's answer as inspiration. I couldn't just use the last image because they don't necessarily load in order. The following script will print the page after all images have loaded (uses jQuery):

var hasPrinted = false;
$(document).ready(function(){
  $('img').load(function(){
    var imgs = $('img');
    var loadedAll=true;
    for(var i=0;i<imgs.length;i++){
      loadedAll &= $(imgs[i])[0].complete;
    }
    if (loadedAll && !hasPrinted) {
      console.log('printing');
      hasPrinted = true;
      window.print();
    }
    else {
      console.log('not all images have loaded');
    }
  })
});
于 2013-07-08T19:36:19.197 回答