I'm a web developer working on a number of in-house apps, and I recently encountered some Chrome-specific behavior with jQuery and CSS I had to work around - I'm wondering if anyone (preferably a developer at Google who works on Chrome) can tell me exactly what's going on under the hood. I've posted the question on Stack Overflow: http://stackoverflow.com/questions/42635777/print-friendly-version-not-working
I've pasted the relevant code below. What I'm doing is using jQuery to toggle a web page between normal view and print-friendly view, without having to refresh the page. I do this by using the jQuery attr() function to change the page's stylesheet link href every time the user clicks a button, switching between "normal.css" and "printFriendly.css". Whenever the user goes to print-friendly, window.print() is called immediately after that command. In Chrome, the print preview immediately comes up, but it comes up without any of the styles from printFriendly.css being applied; sections that should have display:none are visible. And if you print, then the copy comes out looking the same.
On the web page itself, however, beneath the print preview window, you can see the styles have been applied, and nothing is visible that shouldn't be. So, if you cancel the print, then right-click on the page and select "Print..." the print preview window comes up again - this time looking the way it should, and printing the way it should.
Note that this doesn't happen in Firefox; in FF, when the user clicks on the button to go to print-friendly, a print dialog box comes up, the user clicks "OK", and the page prints looking the way it should. For Chrome, I found a solution, albeit a hacky one, by using javascript's setTimeout() function to delay the window.print() call by 100 milliseconds. Doing this makes the print preview come up looking the way it should the first time. So, I figure there's a race condition of some kind, although I don't know why - the js should be synchronous, as far as I can tell.
$('#printOnlyBtn').click(function(){
if ($('#mainStylesheetLink').attr('href') == 'normal.css' {
//switch to print-friendly css file and print
doPrint();
}
else {
//switch back to normal css file
$('#mainStylesheetLink').attr('href', 'normal.css');
}
});
function doPrint(){
$('#mainStylesheetLink').attr('href', 'printFriendly.css');
setTimeout(window.print, 100);