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

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

        });

以上是window.open()与document.write()一起使用,document.write()报Cannot read properties of null 错误的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>