Mfffffffffffff
Mfffffffffffff

Reputation: 13

Print to client side on window.load

I'm trying to print to the client's printer immediately upon a page loading, using the following:

function openWin() {
    var printWindow = window.open();
    printWindow.document.write('<html><head><title>Test Page</title>');
    printWindow.document.write('</head><body>');
    printWindow.document.write("Name: <?php echo $firstname . " " . $lastname; ?><br />Spouse: <?php echo $sfirstname . " " . $slastname; ?><br />Address: <?php echo $_POST['address'] ?><br />City/State/Zip:  <?php echo $_POST['city'] . ", " . $_POST['state'] . " " . $_POST['zip'] ?><br />");  
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
    printWindow.close(); 
}

To get the function to fire, I'm using

$(window).load(function(){
    openWin();
});

When the document opens, nothing prints - i.e., the openWin() function doesn't fire. I've tried creating a button for it and using trigger to click the button when the window loads. I've also tried setTimeout() to delay a while so the page can continue loading, etc. Nothing works.

I get this error at the console:

application2.php:240 Uncaught TypeError: Cannot read property 'document' of null

BUT, when I simply enter openWin() at the console, the print page opens properly.

Any help would be appreciated.

Upvotes: 1

Views: 2765

Answers (2)

Jorge Guerrero
Jorge Guerrero

Reputation: 343

Keep in mind that most browsers blocks popups when these are not triggered by an user action like a click. A way to do it, is calling the 'window.print' in the load event and finally make a redirect to some page that you need.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
  <script type="text/javascript">

$(window).load(function(){
        window.document.write('<html><head><title>Test Page</title>');
        window.document.write('</head><body>');
        window.document.write("Name: Some valid html<br />");  
        window.document.write('</body></html>');
        window.document.close();
        window.print();
        window.location.replace("http://stackoverflow.com");
});
  </script>
</head>
<body>

</body>
</html>

Upvotes: 2

dotsinspace
dotsinspace

Reputation: 691

It worked when for me when i replaced $(window).load with $(document).ready. $(window).load works when dom loaded completely. and $(document).ready works when everything is loaded (img etc...)

Upvotes: 0

Related Questions