简体   繁体   English

在JavaScript缺少图片的情况下打印弹出窗口

[英]Print popup in JavaScript missing images

I want to open a new window/tab, put some HTML in the document, then bring up the browser print dialog to print that new window. 我想打开一个新窗口/选项卡,在文档中放入一些HTML,然后调出浏览器打印对话框以打印该新窗口。 I am using the following to accomplish this: 我正在使用以下方法来完成此任务:

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

Where html contains: 其中html包含:

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

This all works, the window pops up, and the print dialog is shown for the new page, however, for some reason the browser isn't waiting for all the images on the page to load before showing the print dialog. 所有这些都有效,弹出窗口,并显示新页面的打印对话框,但是,由于某种原因,浏览器在显示打印对话框之前没有等待页面上的所有图像加载。 It's causing some images not to print. 这导致某些图像无法打印。

There are many images, and they are dynamically generated on the server side (takes about 1 sec each to load). 有很多映像,它们是在服务器端动态生成的(每个映像大约需要1秒钟才能加载)。 How do I force the browser to only print once all the images are loaded? 如何强制浏览器仅在加载所有图像后才打印?

This happens in Chrome and Firefox that I've confirmed. 我已经确认,这会在Chrome和Firefox中发生。 I appreciate any help. 感谢您的帮助。

Try changing it from the body.onload event to the window.onload event. 尝试将其从body.onload事件更改为window.onload事件。

w.window.onload = window.print()

Or something like that. 或类似的东西。

Try putting your printer call in an onload event for the last image. 尝试将您的打印机呼叫置于最后一个图像的onload事件中。

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

EDIT: 编辑:

Full answer by OP as seen below: OP的完整答案如下所示:

I came up with the following script using @chockleyc's answer as inspiration. 我以@chockleyc的答案为灵感提出了以下脚本。 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): 加载所有图像后(使用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');
    }
  })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM