【问题标题】:Cannot read property 'document' of null when try to print html document尝试打印 html 文档时无法读取 null 的属性“文档”
【发布时间】:2017-11-01 10:30:44
【问题描述】:

我正在使用 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);
}

但我犯了这个错误

错误类型错误:无法读取 null 的属性“文档”。

我该如何解决这个问题?

【问题讨论】:

  • popupWin.documentElement.open 也许?
  • 感谢您的回复。我仍然遇到同样的错误吗?

标签: javascript angular


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    来自 MDN

    表示新创建的窗口的 Window 对象。如果 无法打开窗口,返回值为空。这 返回的 Window 引用可用于访问属性和方法 新窗口只要符合同源政策 安全要求。

    如果返回null,则表示弹窗已被浏览器屏蔽。可能用户尚未初始化该操作?

    【讨论】:

      【解决方案3】:

      修复的简单解决方案是将 open() 函数重命名为其他名称,这将修复您的错误消息。

      在您的 chrome 检查器控制台中复制/粘贴。

      function print() {
          let 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()">test</body>
            </html>`
          );
          popupWin.document.close();
      }
      function openOther(){
        //I called Api using service
         let scope=this;
         setTimeout(function() { scope.print(); }, 3000);
      }
      openOther()
      

      在您的情况下,this 是 Window 对象,使用 open 名称可以覆盖本机 Window.open 函数。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2013-09-28
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      相关资源
      最近更新 更多