4

I want print a page without open it on all major browsers. (Safari, IE, firefox, Chrome and Opera)

I tried that but doesn't work on firefox (Error : Permission denied to access property 'print') :

<!DOCTYPE html>
    <html>
        <head>
            <title>Test</title>
            <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
            <link rel="alternate" media="print" href="print.php"> 
            <script type="text/javascript">
                function impression() {
                window.frames[0].focus();
                window.frames[0].print();
                }
            </script>
        </head>
        <body>


            <iframe height="0px" src="print.php" id="fileToPrint" style="visibility: hidden"></iframe>
            <a href="javascript:impression()">Imprimer</a>
        </body>
    </html>

This code works on Chrome.

I want one thing like that for all browsers to mention but I don't know how.

Is there another way to do that?

Lynxi
  • 817
  • 13
  • 39

2 Answers2

1

Create an iframe, hide it, and then call the proper print functions. The execCommand should work for all versions of IE.
Mind you: $.browser won't work for newer versions of jQuery and should be avoided. Use your preferred way of detecting features.

var ifr = createIframe();
ifr.hide();

if ($.browser.msie) {
    ifr.contentWindow.document.execCommand('print', false, null);
} else {
    ifr.contentWindow.focus();
    ifr.contentWindow.print();
}

This was developed for IE, FF and Chrome. I have no idea how well this will work for Safari and Opera, but it might give you some ideas.

Edit: as adeneo correctly pointed out, $.browser is deprecated and should be avoided. I updated my statement. I'll leave my code untouched, as it still expresses the correct intent.

0

You can try this code, but it's Javascript ;

<script language="JavaScript">
var gAutoPrint = true; // Tells whether to automatically call the print function

function printSpecial()
{ 
if (document.getElementById != null)
{
var html = '<HTML>\n<HEAD>\n';

if (document.getElementsByTagName != null)
{
var headTags = document.getElementsByTagName("head");
if (headTags.length > 0)
html += headTags[0].innerHTML;
}

html += '\n</HE>\n<BODY>\n';

var printReadyElem = document.getElementById("printReady");

if (printReadyElem != null)
{
html += printReadyElem.innerHTML;
}
else
{
alert("Could not find the printReady function");
return;
}

html += '\n</BO>\n</HT>';

var printWin = window.open("","printSpecial");
printWin.document.open();
printWin.document.write(html);
printWin.document.close();
if (gAutoPrint)
printWin.print();
}
else
{
alert("The print ready feature is only available if you are using an browser. Please update your browswer.");
}
}

</script>
mortiped
  • 869
  • 1
  • 6
  • 28