首页 > 解决方案 > Apps 脚本自定义模式对话框中的 window.print()

问题描述

我正在通过运行 onEdit 触发器的 Apps 脚本在 Google 表格中创建一个自定义模式对话框弹出框。这个想法是,用户单击列中某个单元格中的复选框。触发器检测到此编辑,并调用利用 Apps Script UI 和 HtmlService 类的函数。这将创建一个使用一些 html 构建的简单模式对话框。在 html 中,我有一个调用 window.print() 的按钮。但是,通过调用它,什么也没有发生。我认为这是因为同源政策问题。Html 服务很可能使用另一个域名来启动与 docs.google.com 不同的对话框。因此,窗口调用可能存在问题。还有其他方法吗?如何为 Google Apps 创建自定义打印?我已经看到了一些动态创建 pdf 并打印的变体,

单击复选框时,将调用以下函数:

function openDialog() {

  var html = HtmlService.createHtmlOutputFromFile('html') ;

  SpreadsheetApp.getUi() 
      .showModalDialog(html, 'Print Receipt');
}

这是以下html:

<!DOCTYPE html> 
  <html>  
    <head><base target="_top">  
    </head>  
    <body>  
      <img src="https://i.imgur.com/someimage.png" alt="Logo" width="100" height="100">   
      <h3>testing</h3>   
      <button onclick="print()">Print</button> 
    </body>   
    <script>  
      function print() {    
        window.print();  
      }   
    </script> 
  </html>'); 

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


您应该考虑将打印函数重命名为其他名称,例如“printPage”,否则它可能会调用本机打印 API。此外,可能会删除 HTML 中的额外括号。

<!DOCTYPE html> 
  <html>  
    <head><base target="_top">  
    </head>  
    <body>  
      <img src="https://i.imgur.com/someimage.png" />   
      <h3>testing</h3>   
      <button onclick="printPage()">Print</button> 
    </body>   
    <script>  
      function printPage() {    
        window.print();  
      }   
    </script> 
  </html>

推荐阅读