valen
valen

Reputation: 845

Printing custom url with javascript not working

I'm trying to print another page on my domain by passing window.open the url, and using window.focus, window.print to print. However, the print preview shows only an empty page. I'm guessing I have to wait until the page is loaded, but I'm not sure exactly how to do this. Here's the code:

var newWin=window.open('http://mydomain.com');
newWin.focus(); 
newWin.print(); 
newWin.close();

I've tried stuff like

newWin.onload() {
    newWin.print();
});

to no avail.

Edit 1:

var newWin=window.open('http://localhost:76');
newWin.focus(); 
newWin.onload = newWin.print();
newWin.close();

Same problem persists

Edit 2:

var newWin=window.open('http://localhost:76');
newWin.focus(); 
newWin.body.onload = newWin.print();

Adding newWin.close() here causes the print function to bug out and only print the
title of the page. Otherwise, the page is printing properly with this

Edit 3:

function printWin(newWin) {
    newWin.print();
    newWin.close();
}

var newWin = window.open('http://localhost:76');
newWin.focus();
newWin.body.onload = printWin(newWin);

This causes the print to happen prematurely like before, previewing an empty page. wtf :(

Upvotes: 1

Views: 1049

Answers (1)

user1330271
user1330271

Reputation: 2691

Open the popup. Then check if the popup is ready. When it's ready, inject a javascript.

<script type="text/javascript">

    var popup = window.open("b.htm");
    var body;
    function check() {
        body = popup.document.getElementsByTagName("body");
        if (body[0] == null) {
            setTimeout(check, 50);
        } else {
            var n = popup.document.createElement("script");
            n.src = "printandclose.js";
            body.appendChild(n);
        }
    }
    check();

</script>

printandclose.js

window.print();
window.open("", "_self");
window.close();

Let me know if it works. If you don't add window.open("", "_self"); a alert will popup telling the user that the window is about to close.

Upvotes: 2

Related Questions