Pass google script value to html

2019-01-29 03:36发布

问题:

I have been looking at various other solutions posted here but none of them seem to work for me.

I'm trying to pass a variable from my google script (which is originally stored in google's PropertiesService) to my html, because I want to use previously saved data as values for my text input box (showing the previously saved data).

This is my gs file (minus unrelated parts):

function openSettings() {

  var htmlTemplate = HtmlService.createTemplateFromFile('settingsForm')


  var userProperties = PropertiesService.getUserProperties();
  var time = userProperties.getProperty('selectedTime');
  htmlTemplate.timehtml = time;

  var html = htmlTemplate.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
    .setTitle('Settings')
    .setWidth(300)
  SpreadsheetApp.getUi()
    .showSidebar(html);
  return html
}

function processForm(form) {

  var userProperties = PropertiesService.getUserProperties();

  var time = userProperties.getProperty('selectedTime');
  time = form.time;
  userProperties.setProperty('selectedTime', time);
}

And this is my html file (left out other unrelated parts):

<!DOCTYPE html>

<html>

<div>
 <form>
   <input type="text" name="time" id="time" style="width: 40px;">
   <br><br><input type="button" class="action" onClick="writeFormData(); 
   alert('submitted')" value="Submit"/>
 </form>
</div>

<script>
  var timeInput = document.getElementById("time");
  var timehtml = time;
  timeInput.value = timehtml;
</script>

<script type="text/javascript">
       function writeFormData() {
           google.script.run.processForm(document.forms[0]);
       }
</script>

</html>

Perhaps my whole approach is wrong. But what I'm trying to do is store the user choices (might want to change userProperties to documentProperties, to make the settings document specific) in Google's PropertiesService and then save these values when the submit buttons is pressed in a sidebar. Next time when the sidebar is opened these saved settings should be shown.

回答1:

You are on the right track. Because you've already passed the variable to the HtmlTemplate object, the only remaining step is to use GAS template engine to render it.

.GS file

...
htmlTemplate.timehtml = time;
...

HTML template

   <input type="text" name="time" id="time" value="<?!= timehtml ?>">

More on templated HTML in GAS here https://developers.google.com/apps-script/guides/html/templates

The reason your code doesn't work is that you are passing the variable by setting the property of the HtmlTemplate object. HtmlTemplate and HtmlOutput objects exist only in the context of GAS Script Editor runtime. Your browser ends up getting the HTML string which it then parses into DOM elements and renders. At that stage, any GAS-related context is lost, with your locally installed browser software being the new runtime environment for your code. That's the reason why you can't reference the 'timehtml' variable.