Use the onbeforeprint attribute to execute a script before the document is printed in HTML.
Example
You can try to run the following code to implement onbeforeprint attribute −
<!DOCTYPE html>
<html>
<body onbeforeprint = "display()">
<script>
function display() {
alert("The document will now print.");
}
</script>
</body>
</html>