snowflakekiller
snowflakekiller

Reputation: 3568

Wait for html to write to window before calling window.print()

I have this javascript code attached that puts some content into a popup window and then tries to print it:

$(".print_friendly_popup").click(function() {
    var target = $(this).data('print-target');
    var left = (screen.width/2)-(500/2);
    var top = (screen.height/2)-(500/2);
    var win = window.open("", "test", "width=500,height=500 top=" + top + ", left=" + left);

    if(target == 'review') {
        win.document.write($('#print_friendly_review').html());
    } else if(target == 'essay') {
        win.document.write($('#print_friendly_essay').html());
    }
    win.print();
    win.close();
});

The problem is sometimes the call to win.document.write takes too long and the window tries to print a blank screen. How do I wait for window.document to be written to before firing print?

Upvotes: 0

Views: 3350

Answers (2)

Ahmed Nuaman
Ahmed Nuaman

Reputation: 13241

So how about this: create some sort of "checker" to see if the window has the content in it, for example:

var checkForContent = function () {
  setTimeout(function () {
    var content = win.document.querySelector('body').innerHTML

    if (content.length) {
      win.print()
      win.close()
    } else {
      checkForContent()
    }
  }, 200)
}

This way you're politely waiting for the content to render before printing.

Upvotes: 2

T.Todua
T.Todua

Reputation: 56487

Try

win.onload = function(e){ 
    //..... your codes 
}

Upvotes: 1

Related Questions