when printing a page, the javascript code seems to be executed.
how can I determine, if the page is currently being printed? I do some js-resizing, and have to handle printing a little bit different.
JavaScript Print 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.
JavaScript helps you to implement this functionality using the print function of window object. The JavaScript print function window. print() prints the current web page when executed. You can call this function directly using the onclick event as shown in the following example.
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.)
To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.
You can't, except for IE browsers. No other browser has a before print event. You can, however, target a specific stylesheet to only apply while printing:
<!-- In head -->
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
This stylesheet will be applied before printing. This allows you to perform some amazing changes, including hiding major sections, moving items around, and performing print-only styling, such as page breaks.
Another option is to provide the user with a "Print this Page" button. That button can handle your JavaScript, call window.print()
, and revert the changes:
function printMe() {
// perform changes
window.print();
// revert changes
}
The window.print()
method always blocks (in every browser I've tested), so it's safe to immediately revert the changes afterward. However, if the user choose to print via the menu or toolbar, you are out of luck.
One way I handled that case in a complex web-app was to have a print stylesheet that hid everything but a special DIV. If the user clicked print, they would get a warning message. If they clicked the print button, then that div would be populated with the correct information. It's not great, but at least they didn't get several pages of garbage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With