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
484 views
in Technique[技术] by (71.8m points)

html - Printing a (part of) webpage with Javascript

I am aware of two ways of calling the "print" dialog of browser (I used the Search, of course):

  • document.print()
  • document.execCommand('print', false, null)

What is the difference between them? Support across browsers? Papers, docs or standards? Which is more correct thing to use?

Another question: what is the most straight way to print given part of a webpage? I know we can create new window or iframe to call any of two print methods above. Which one has less pitfalls?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I've tested different ways of printing part of webpage across browsers: Chrome, Firefox, Opera (12 and new), IE11, 10, 9 and 8. I've tried to create new window, new iframe, or use existing iframe on the page. And then tried .print() and .execCommand('print').

Note: Keep in mind that .print() is called on window, and .execCommand() is called on document.

Code used for testing can be found here

Correct me if my testing code is wrong, I just wanted to find the clearest way to do the job. My conclusions:

  • Opera 12 can not print part of a webpage (?)
  • IEs don't print() iframes and windows, except current window.
  • Calling print() on documents inside iframes or created windows in IEs breaks the print() on current document. Be careful!
  • jQuery plugin printThis uses tricks for IE to do the job, and it just works. The only exception is Opera 12. By the way, this plugin uses print().
  • execCommand('print') works almost everywhere and with any approach (iframes, window). It's not supported by Firefox though.
  • execCommand() returns false if call was unsuccessful, so if you don't want to use plugins and magic tricks, create window or iframe, call execCommand('print') and if it returns false, call print().

One more thing:

Creating an iframe is tricky: you can't access its window or document directly (yes, you have ContentDocument property, which behaves differently across browsers). You should name it and then call window.frames[name] to get window object from that iframe. Do not try to call window.frames(id) - it will return the iframe.


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

...