Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript new window open and print css loading

I want to use a new window to print part of HTML.

    var cssLink = document.getElementByTagName('link')[2];

    var prtContent = document.getElementById('print_body');

    var WinPrint = window.open('','','left=0,top=0,width=1000,height=auto,toolbar=0,scrollbars=0,status=0');

    WinPrint.document.write(prtContent.innerHTML);
    WinPrint.document.getElementsByTagName('head')[0].appendChild(link);
    WinPrint.document.close();

    WinPrint.focus();
    WinPrint.print();

But sometimes when WinPrint going to do system print, the CSS file still not loaded.

How could I fix it?

like image 853
iamshaojin Avatar asked Sep 28 '26 11:09

iamshaojin


1 Answers

It sounds like sometimes the browser isn't loading the CSS file in time for you to print. You can run your printing code only after the css file is loaded, like so:

var cssElement = document.getElementsByTagName('link')[2].cloneNode();

var prtContent = document.getElementById('print_body');

var WinPrint = window.open('','','left=0,top=0,width=1000,height=auto,toolbar=0,scrollbars=0,status=0');

WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();

cssElement.addEventListener('load', function () {
  WinPrint.focus();
  WinPrint.print();
});

WinPrint.document.head.appendChild(cssElement);
like image 160
Steve Avatar answered Oct 01 '26 03:10

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!