gpt4 book ai didi

javascript - 尝试打印 html 文档时无法读取 null 的属性 'document'

转载 作者:太空狗 更新时间:2023-10-29 17:36:51 26 4
gpt4 key购买 nike

我正在使用 angualr 2。

我正在尝试打印 html div。

这是我的代码

<div id="print-section">
// Html code
</div>
<button (click)="open()">print</button>

print(): void {
let printContents, popupWin;
printContents = document.getElementById('print-section').innerHTML;
popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print tab</title>
</head>
<body onload="window.print();window.close()">${printContents}</body>
</html>`
);
popupWin.document.close();
}

这是我的 open()

open(){
//I called Api using service
let scope=this;
setTimeout(function() { scope.print(); }, 3000);
}

但是我得到了这个错误

ERROR TypeError: Cannot read property 'document' of null.

我该如何解决这个问题?

最佳答案

被浏览器拦截了。 window.open 只有在被用户操作调用时才不会被阻止,例如在点击事件中,由 native 浏览器事件发出。

关于javascript - 尝试打印 html 文档时无法读取 null 的属性 'document',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47052785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com