Auto start print html page using javascript
147,213
Solution 1
<body onload="window.print()">
or
window.onload = function() { window.print(); }
Solution 2
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>
Solution 3
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>
Solution 4
Use this script
<script type="text/javascript">
window.onload = function() { window.print(); }
</script>
Solution 5
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();
Author by
fmsf
CEO / CTO at https://temploescondido.pt/ Engineer at Palantir
Updated on July 24, 2022Comments
-
fmsf almost 2 years
Is there anyway to automatically run
javascript:window.print()
when the page finishes loading? -
Deva over 15 yearsThe second variation is the preferred method.
-
Spudley about 12 yearsbetter to use
<script type="text/javascript">
rather than using the deprecatedlanguage
attribute. -
fmsf about 12 yearsIf that's not in the end of the HTML it will start the printing process before the page is loaded.
-
elipoultorak over 8 yearsWhy not
window.onload = window.print;
-
jave.web over 5 years@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 :)