Window.print Prints Incorrect Content in Google Chrome

I’m having trouble getting Google Chrome to print the correct content when I change the content of a modal page with JavaScript. This is my code:

JavaScript:

function printCoupon(couponID)
{
  var originalContents = document.body.innerHTML;
  var printable = document.getElementById(couponID);
  var printContents = printable.innerHTML;

  document.body.innerHTML = printContents;

  window.print();

  document.body.innerHTML = originalContents;
  document.getElementById(couponID).scrollIntoView(true);
}

HTML:

<body>
  <div id="coupon1"><p>Coupon 1 contents</p></div>
  <div><a href="javascript:void(0)" onclick="printCoupon('coupon1');return false;">Print Coupon</a></div>
  <div id="coupon2"><p>Coupon 2 contents</p></div>
  <div><a href="javascript:void(0)" onclick="printCoupon('coupon2');return false;">Print Coupon</a></div>
</body>

This works in IE8 and FF 3.6, but Chrome 16 prints the original content, not the printable content.

Try seeing how things go when you add in a small delay.


setTimeout(window.print, 500);

When I do that it doesn’t work in any browser. It performs the next command(s) before window.print. Your suggestion was helpful, though, in that it pointed out what was happening in Chrome. Is there a way to set a timeout between window.print and the following command?

Only by placing everything that must follow the print command in a separate piece of code, such as with:


setTimeout(function () {
    window.print();
    ...
}, 500);

I’m not in a position to test things right now, but that’s the theory.

Thanks, paul_wilkins!! The solution was to split the script into three scripts (before, during and after print) and use setTimeout on the second two. It works perfectly, now.