首页 新闻 会员 周边

window.open()与document.write()一起使用,document.write()报Cannot read properties of null 错误

0
[已解决问题] 解决于 2021-11-03 17:25

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();

        });
cker90的主页 cker90 | 菜鸟二级 | 园豆:258
提问于:2021-11-03 11:03
< >
分享
最佳答案
0

我在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>
奖励园豆:5
wang_yb | 老鸟四级 |园豆:4891 | 2021-11-03 15:30

找到原因了,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();

        });
cker90 | 园豆:258 (菜鸟二级) | 2021-11-03 17:19
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册