Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

printing - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...