我试图在加载页面时立即打印到客户端的打印机,使用以下方法:
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();
}为了激活这个函数,我用
$(window).load(function(){
openWin();
});当文档打开时,什么都不会打印--即openWin()函数不会触发。我尝试为它创建一个按钮,并在窗口加载时使用触发器单击该按钮。我还尝试过setTimeout()延迟一段时间,这样页面就可以继续加载,等等。
我在控制台得到了这个错误:
Application2.php:240个未登录的TypeError:无法读取空的属性‘文档’
但是,当我在控制台输入openWin()时,打印页面就会正常打开。
任何帮助都将不胜感激。
发布于 2017-04-16 17:58:52
请记住,当弹出窗口不是由用户操作(如单击)触发时,大多数浏览器都会阻止弹出窗口。一种方法是在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>发布于 2017-04-16 17:05:30
当我将$(window).load替换为$(document).ready时,它起了作用。$(window).load在dom完全加载时工作。和$(文档).ready工作时,所有的东西加载(img等.)
https://stackoverflow.com/questions/43439680
复制相似问题