Is there anyway to automatically run javascript:window.print()
when the page finishes loading?
6 Answers
<body onload="window.print()">
or
window.onload = function() { window.print(); }

- 316,276
- 54
- 369
- 333
-
8The second variation is the preferred method. – staticsan Oct 27 '08 at 22:24
-
6Why not `window.onload = window.print;` – elipoultorak Mar 06 '16 at 14:09
-
@elipoultorak not this case specifically, but some calls for native functions that are not direct are causing "Illegal invocation" error, so this is generally discouraged so not used as much :) – jave.web Nov 15 '18 at 11:00
-
@elipoultorak @jave.web `window.onload = window.print.bind();` ;) – Wilhelmina Lohan Apr 18 '23 at 20:19
The following code must be put at the end of your HTML file so that once the content has loaded, the script will be executed and the window will print.
<script type="text/javascript">
<!--
window.print();
//-->
</script>

- 1,426
- 10
- 25

- 227
- 2
- 4
-
3
-
6If that's not in the end of the HTML it will start the printing process before the page is loaded. – fmsf May 07 '12 at 05:53
Add the following code in your HTML page, and it will show print preview on page load.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function () {
window.print();
});
</script>

- 181
- 1
- 3
- 12
Use this script
<script type="text/javascript">
window.onload = function() { window.print(); }
</script>

- 1,414
- 16
- 22
If what you want is to open a separate window from the web browser you can use this:
window.open(basePath + "Controller/Route/?ID=" + param, '_blank').print();

- 141
- 1
- 2
- 14
For me, adding <script>window.print();</script>
to the end of the page worked.
I didn't need the type="text/javascript"
attribute, or even for the page to be wrapped in a <body>
tag. However, all of my previous attempts to intuitively use the answers suggested here, of just writing window.onload=window.print
or longer versions such as window.onload=()=>window.print();
did not work, and of course calling print on the newly created window does not wait for the contents to load.

- 945
- 12
- 26