var newWindow = window.open("打印窗口", "_blank");
var docStr = document.getElementById('DIVContentPreview').innerHTML;
newWindow.document.write(docStr);
报错
Index:970 Uncaught TypeError: Cannot read properties of null (reading 'document')
找到原因了,window.open("打印窗口", "_blank")被阻塞了,打不开
//当页面内容太多的时候,这个方法会阻塞window.open返回null
$("#DIVContentPreview").load(url, postData, function () {
var newWindow = window.open("打印窗口", "_blank");
var docStr = document.getElementById('DIVContentPreview').innerHTML;
newWindow.document.write(docStr);
newWindow.print();
newWindow.close();
$("#DIVContentPreview").hide();
});
正确用法(打开窗口移前):
var newWindow = window.open("打印窗口", "_blank");
$("#DIVContentPreview").load(url, postData, function () {
var docStr = document.getElementById('DIVContentPreview').innerHTML;
newWindow.document.write(docStr);
newWindow.print();
newWindow.close();
$("#DIVContentPreview").hide();
});
我在chrome试了下可以运行的,可能浏览器会阻止弹出窗口,要允许下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<h1>testest</h1>
<div id="DIVContentPreview">aaabbbccc</div>
<script type="text/javascript">
var newWindow = window.open("打印窗口", "_blank");
var docStr = document.getElementById('DIVContentPreview').innerHTML;
console.log(newWindow)
newWindow.document.write(docStr);
</script>
</body>
</html>
找到原因了,window.open("打印窗口", "_blank")被阻塞了,打不开
//当页面内容太多的时候,这个方法会阻塞window.open返回null
$("#DIVContentPreview").load(url, postData, function () {
var newWindow = window.open("打印窗口", "_blank");
var docStr = document.getElementById('DIVContentPreview').innerHTML;
newWindow.document.write(docStr);
newWindow.print();
newWindow.close();
$("#DIVContentPreview").hide();
});
正确用法(打开窗口移前):
var newWindow = window.open("打印窗口", "_blank");
$("#DIVContentPreview").load(url, postData, function () {
var docStr = document.getElementById('DIVContentPreview').innerHTML;
newWindow.document.write(docStr);
newWindow.print();
newWindow.close();
$("#DIVContentPreview").hide();
});