Javascript 在window.load上打印到客户端
我正在尝试在加载页面后立即使用以下方法打印到客户端打印机:Javascript 在window.load上打印到客户端,javascript,jquery,printing,Javascript,Jquery,Printing,我正在尝试在加载页面后立即使用以下方法打印到客户端打印机: function openWin() { var printWindow = window.open(); printWindow.document.write('<html><head><title>Test Page</title>'); printWindow.document.write('</head><body>'); p
function openWin() {
var printWindow = window.open();
printWindow.document.write('<html><head><title>Test Page</title>');
printWindow.document.write('</head><body>');
printWindow.document.write("Name: <?php echo $firstname . " " . $lastname; ?><br />Spouse: <?php echo $sfirstname . " " . $slastname; ?><br />Address: <?php echo $_POST['address'] ?><br />City/State/Zip: <?php echo $_POST['city'] . ", " . $_POST['state'] . " " . $_POST['zip'] ?><br />");
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
文档打开时,不会打印任何内容,即openWin()
函数不会启动。我尝试为它创建一个按钮,并在窗口加载时使用触发器单击按钮。我还尝试了setTimeout()
延迟一段时间,以便页面可以继续加载,等等。没有任何效果
我在控制台上收到此错误:
application2.php:240未捕获类型错误:无法读取null的属性“document”
但是,当我在控制台简单地输入openWin()
时,打印页面会正确打开
任何帮助都将不胜感激。当我替换$(窗口)。加载$(文档)。准备好了$(窗口)。当dom完全加载时,加载工作。和$(document).ready在加载所有内容(img等)时起作用。请记住,大多数浏览器在弹出窗口不是由用户操作(如单击)触发时会阻止弹出窗口。 一种方法是在load事件中调用“window.print”,最后重定向到您需要的某个页面
<!DOCTYPE html>
<html>
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(window).load(function(){
window.document.write('<html><head><title>Test Page</title>');
window.document.write('</head><body>');
window.document.write("Name: Some valid html<br />");
window.document.write('</body></html>');
window.document.close();
window.print();
window.location.replace("http://stackoverflow.com");
});
</script>
</head>
<body>
</body>
</html>
$(窗口)。加载(函数(){
window.document.write('testpage');
window.document.write(“”);
window.document.write(“名称:一些有效的html
”);
window.document.write(“”);
window.document.close();
window.print();
window.location.replace(“http://stackoverflow.com");
});
谢谢。你说得对。但昨天,我放弃了这个想法,做了一个变通,为用户添加了一个“强制”打印按钮。
<!DOCTYPE html>
<html>
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(window).load(function(){
window.document.write('<html><head><title>Test Page</title>');
window.document.write('</head><body>');
window.document.write("Name: Some valid html<br />");
window.document.write('</body></html>');
window.document.close();
window.print();
window.location.replace("http://stackoverflow.com");
});
</script>
</head>
<body>
</body>
</html>