user1930254 user1930254 - 1 month ago 9
Javascript Question

Chrome print blank page

I have an old javascript code to print images, if a user clicks on the thumbnail. It used to work just fine, but lately (only in Chrome!) there is a blank page in preview.

Here is a demonstration in JsBin:
Click the printer icon. Now try it in Firefox; it will work as expected.

Chrome: 41.0.2272.89 m

Firefox: 30.0, 36.0.1

function newWindow(src){

win ="","","width=600,height=600");
var doc = win.document;
// init head
var head = doc.getElementsByTagName("head")[0];
// create title
var title = doc.createElement("title");
title.text = "Child Window";
// create script
var code = "function printFunction() { window.focus(); window.print(); }";
var script = doc.createElement("script");
script.text = code;
script.type = "text/javascript";
// init body
var body = doc.body;
doc.write('<img src="'+src+'" width="300">');

if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {


} else {


It looks like it's attempting to print before the <img> has loaded, move the call to print inside an event handler for the load event of window by opening the link as a data URI or Blob, for example

var code = '\
    function printFunction() {\
    window.addEventListener(\'load\', printFunction);\
        <body><img src="'+src+'" width="300"></body>\
    </html>';'data:text/html,' + code, '_blank', 'width=600,height=600');

Don't forget you may need to HTML encode the tags in code

You could probably just listen for load on the <img> instead, but if you ever do anything more complicated than tring to print a single image you may find it breaks again in future

doc.write('<img onload="printFunction();" src="'+src+'" width="300">');

Where printFunction is the print function for all browsers