'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.
Solution 1:[1]
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"}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |


