work with Google Apps Script's HtmlService

2019-04-17 15:08发布

问题:

I see many examples of using UiApp, but can't figure out how to use HtmlService. For example:

var app = UiApp.getActiveApplication();
...
app.createListBox().setName('list').setId('list')
...
app.getElementById('list').clear(); 
app.getElementById('list').addItem(...);

With HtmlService, how can I create an HTML file with such a list box? Will I have the same methods?

回答1:

HtmlService is fundamentally different from UiApp, but aligns very closely with "normal" HTML development, as the app is primarily client based. As a result, the methods you may be familiar with from UiApp have no direct equivalent in HtmlService. In fact, the "service" just provides methods to assemble and display user interfaces, and enables secure communication between them and server-side GAS functions.

Here's a simple example that creates a form with a list that is populated using templated HTML. When submitted, it's POSTed to the doPost() function. (NOTE: Publish the script as a web app.)

Code.gs

// Adapted from http://stackoverflow.com/a/11300412/1677912

function doGet(e) {
  var template = HtmlService.createTemplateFromFile('Form.html');
  template.action = ScriptApp.getService().getUrl();
  template.listId = "browsers";
  template.datalist = ["Internet Explorer","Firefox","Chrome","Opera","Safari"];
  return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function doPost(e) {
  var template = HtmlService.createTemplateFromFile('Thanks.html');
  template.browser = e.parameter.browsers;
  return template.evaluate();
}

Form.html

<html>
  <body>
    <h1>Select a browser</h1>
    <form action="<?= action ?>" method="post">
      <input list="<?= listId ?>" name="<?= listId ?>">
      <datalist id="<?= listId ?>">
        <? for (var i=0; i<datalist.length; i++) { ?>
          <option value="<?= datalist[i] ?>">
        <? } ?>
      </datalist> 
      <input type="submit" value="Submit" />
      </form>
  </body>
</html>

Thanks.html

<html>
  <body>
    <h1>Thanks</h1>
    <p>Thank you for your response.</p>
    Browser: "<?= browser ?>"<br/>
  </body>
</html>