简体   繁体   中英

media print doesn't apply style on chrome, but in firefox works perfectly

I have this js function:

function print(title, htmlPrint) {
   var w = window.open('', '', 'width=600,height=750');
   w.document.title = title;
   w.document.write('<link rel="stylesheet" type="text/css" href="print.css" />');
   w.document.write(htmlPrint);
   w.document.close(); // needed for chrome and safari
   w.print();
   w.close();
   return false;
}

and in css I have something like this:

@media print, screen{ 
.....
}

In firefox works as intended: shows title & content, in chrome it just shows me the title and a blank page (the same when I print).

I've tried also with @media print{} or @media all{} and still doesn't work.

I've tried also to add media="print" in <link... /> , doing that it loads the css, but doesn't apply any css to the page.

I've tried also to change the function and use w.document.head.innerHtml and w.document.body.innerHtml - still nothing, has the same behavior as .write() .

What worked for me:

First I had to get the full path of the css file and set the media print in the link tag.

if (/chrome/i.test(navigator.userAgent)) {
     w.document.write('<link rel="stylesheet" type="text/css" href="' + location.protocol + '//' + location.host + (new String(location.pathname.substring(0, location.pathname.lastIndexOf("/")))) + '/print.css" media="print" />');
}else{
     w.document.write('<link rel="stylesheet" type="text/css" href="print.css" />');
}

Then it still didn't work properly and I just found out that the w.close() makes problems to chrome.

if (/chrome/i.test(navigator.userAgent) === false) {
    w.close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM