简体   繁体   中英

Pass js variable in html template to google script

I have a.gs file which create a html page:

function doGet() {
  return HtmlService.createHtmlOutputFromFile('index');
}

doGet();
console.log(myvariable);

and in that index.html file I'll create a variable in tag, which I'd like to pass to my.gs file, for further putting it in google spreadsheet.

<script>
  var myvariable = 10;
</script>

Is there any method that can carry out my need?

Thank you.

Pass variable to htmltemplate

function elfunko() {
  let t = HtmlService.createTemplate('<input type="text" value="<?= globalvariable ?>" />');
  t.globalvariable = "Hello World";
  SpreadsheetApp.getUi().showModelessDialog(t.evaluate(),'title');
}

在此处输入图像描述

Pass variable back to server from html

This one will pass a variable back to server scripts when you click the button on the dialog you can see the result by looking in elfunko1s execution log.

function elfunko() {
  let t = HtmlService.createTemplate('<input type="button" value="<?= globalvariable ?>" onclick="google.script.run.elfunko1({variable:<?= globalvariable ?>})" />');
  t.globalvariable = "Hello World";
  SpreadsheetApp.getUi().showModelessDialog(t.evaluate(),'title');
}

function elfunko1(obj) {
  console.log(JSON.stringify(obj))
}

在此处输入图像描述

Cloud logs
Feb 26, 2022, 8:38:00 PM    Debug   {"variable":"Hello World"}

client to server comm

templated html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM