Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger javascript on print event?

Is it possible to trigger a javascript event when a user prints a page? I would like to remove a dependancy on a javascript library, when a user opts to print a page, as the library is great for screen but not for print.

Any idea how to achieve this?

like image 297
Joe Avatar asked Jun 21 '12 13:06

Joe


People also ask

Can JavaScript trigger events?

HTML events are handled by JavaScript. When an event occurs, it requires some action to be taken. This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document.

Does print work in JavaScript?

JavaScript | Window print() Method. Page print in JavaScript is a simple code in JavaScript used to print the content of the web pages. The print() method prints the contents of the current window.

How do you print a JavaScript command?

JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript. The only exception is that you can call the window.print() method in the browser to print the content of the current window.

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 anyone stumbling upon this answer from Google, let me try to clear things up:

As Ajay pointed out, there are two events which are fired for printing, but they are not well-supported; as far as I have read, they are only supported in Internet Explorer and Firefox (6+) browsers. Those events are window.onbeforeprint and window.onafterprint, which (as you'd expect) will fire before and after the print job.

However, as pointed out in Joe's link (https://stackoverflow.com/a/9920784/578667), that's not exactly how it is implemented in all cases. In most cases, both events fire before the dialog; in others, script execution might be halted during the print dialog, so both events may fire at the same time (after the dialog has been completed).

For more information (and browser support) for these two events:

https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeprint

https://developer.mozilla.org/en-US/docs/DOM/window.onafterprint

The short answer: if you're hoping to interfere with the print flow, don't. If you're hoping to trigger code after printing, it's not going to work how you're wanting; expect poor browser support, and try to degrade gracefully.

like image 113
Aejay Avatar answered Sep 28 '22 00:09

Aejay