Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safari print issue with javascript window.print()

I am having an issue with print on Safari. My System is Windows 7, and this function works fine in all other browsers except Safari. Here is the situation:

window.onload = function(){
    console.log('before print');
    window.print();
}

It won't output the log in console panel, but the print page will appear first, after i choose cancel in print page, the log will be output.

Does any body came up with this issue? Any help will be appreciated.

Updated

Here is the situation i have: We need to print a page whose content can be changed by user by checking and unchecking check box, and only the content part of this page should be printed, so we create a new page that only contains the content for printing. In this page, we need to hide the unnecessary content that is not selected by user, so we need to do some DOM operation before window.print() get called. The console.log() is just an example code for observing. I tried to add an <div id='test'>Test HTML</div> in test HTML and add

var test = document.getElementById('test');
test.style.background = 'yellow';

before window.print();, it shows the same result in my Safari browser, the 'Test HTML' will not turn to yellow until i click cancel button in print panel, so it's not just the console.log issue.

Updated

I am using Safari 5.1.7(7534.57.2) on Windows 7

like image 673
YuC Avatar asked May 13 '14 09:05

YuC


People also ask

Why is JavaScript not working in Safari?

From your Safari menu bar click Safari > Preferences then select the Security tab. Make sure Enable JavaScript and Enable Java are selected.

What does Window Print () do in JavaScript?

print() Opens the print dialog to print the current document. If the document is still loading when this function is called, then the document will finish loading before opening the print dialog.

Can I set the window Print settings with JavaScript?

The window. print() method calls the browser's build in print support plugin to print the current DOM page. you can check the documentation, it doesn't support any argument or settings. to setup the print, you can only utilize the browser's GUI( ex. enable or disable background graphics etc.)


1 Answers

For me, the setTimeout solution didn't work. I found this jQuery plugin https://github.com/jasonday/printThis that has plenty of workarounds for window.print() because it seems not to be fully supported by all browsers.

I took this line that worked for me Safari document.execCommand("print", false, null)

and this worked ok for me for now in safari and chrome

try {
  document.execCommand('print', false, null);
}
catch(e) {
  window.print();
}
like image 81
jperelli Avatar answered Sep 28 '22 09:09

jperelli