David Ho
David Ho

Reputation: 81

window.print() in Apps Script custom modal dialog box

I am creating a custom modal dialog pop up box in Google Sheets via an Apps Script that is running an onEdit trigger. The idea is, the user clicks on a checkbox in some cell in a column. The trigger detects this edit, and calls a function that utilizes Apps Script UI and HtmlService class. This creates a simple modal dialog box that is built using some html. In the html, I have a button that calls window.print(). However, by calling it, nothing happens. I think it's because of the Same Origin Policy issue. The Html Service is likely using another domain name to launch the dialog box that's different than docs.google.com. So, window calls are likely problematic. Is there another way around this? How does one create customized printing for Google Apps? I've seen some variations of creating a pdf on the fly and printing those, but this seems really inefficient for the end user.

When the checkbox is clicked, the following function is called:

function openDialog() {

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

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

Here is the following 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>'); 

Upvotes: 0

Views: 1714

Answers (1)

Amit Agarwal
Amit Agarwal

Reputation: 11278

You should consider renaming the print function to something else, say "printPage" else it may be invoking the native print API. Also, the extra parenthesis in the HTML maybe removed.

<!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>

Upvotes: 2

Related Questions