2

I have a lightbox plugin that required additional option - print the image. So I did a little JS function that print that image as follow:

var headstr="<!DOCUMENT html><html xmlns='http://www.w3.org/1999/xhtml'><head><title></title></head><body>";
var footstr="</body>";
var newstr="<img src=\"[img-location]\" alt='courses' />";
document.body.innerHTML=headstr+newstr+footstr;
window.print();
window.location.reload();

The problem is that when the user press on the print button, in chrome it opens a new window (chrome print page) and in it, it says - print preview failed. In firefox and IE8 it works just fine...

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Nir
  • 2,497
  • 9
  • 42
  • 71

2 Answers2

3

I don't know if this is what caused your failure, but if window.print() is called from an <input type="submit"> within a form with method="post" (i.e. every asp.net page ever) then Chrome print preview wigs out.

The solution to this is to add return false; after window.print() so that the page doesn't post back.

<html>
 <head>
 </head>
 <body>
  <form method="post" action="test.html">
   <p>This is only a test.  Had this been a real emergency....</p>

    <!--This doesn't work -->  
    <!-- <input type="submit" onclick="JavaScript:window.print();">-->  

    <!--But this does -->
    <input type="submit" onclick="JavaScript:window.print();return false;">

 </form>
</body>
</html>
personaelit
  • 1,633
  • 3
  • 31
  • 59
0

I'm not sure if this is the problem, but you're creating invalid html. For one, you don't close the <html> tag. In addition, you're putting an html and head tag within your body.

James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • I added closing html tag but what is wrong with: - aka - your second remark. BTW putting just the closing html still didnt help. – Nir Aug 04 '11 at 18:32
  • That structure is fine for an entire page, but you are inserting that inside of your body `document.body.innerHTML`. So you already have `` and inside of that you're putting another `etc.` – James Montagne Aug 04 '11 at 18:35
  • Oh right, can I do document=headstr+newstr+footstr? I want it because it also delete the existing header content – Nir Aug 04 '11 at 18:40
  • This question seems to answer that: http://stackoverflow.com/questions/4292603/replacing-entire-page-including-head-using-javascript – James Montagne Aug 04 '11 at 18:45
  • I had also missing closing img tag, but still chrome shows the same page, when I go see the page preview source code - it seems like the javascript changes I did - didnt take any affect, but after that the page get changed and if I press then print it shows it as it should! – Nir Aug 04 '11 at 20:01
  • Don't know whether this is related to this specific issue or not... at any case, I see many people seem to have troubles printing on Chrome from JS... http://www.google.as/support/forum/p/Chrome/thread?tid=09f495e9ca1a2400&hl=en – maraspin Sep 17 '11 at 19:02