简体   繁体   中英

How can I use the variable in the gs file as the input value in the HTML file in Google Apps script?

The variable fieldName for testGetFieldName function is located at Code.gs

I want to insert it into the input value of the index.html file.

But if I open Sidebar using testSetValue, the value comes out as undefiend.

How can I get the variable 'Account' to come out with Value?

The code I wrote is as follows.

//code.gs
function testGetFieldName(){
  var fieldName = 'Account';
  return fieldName;
}

function testSetValue(){
  var html = HtmlService.createTemplateFromFile('index');
  var output = html.evaluate()
      .setTitle('MySidebar')
      .setWidth(400)
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi().showSidebar(output);
}

index.html

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
</head>

<body>
  <input type="text" id ='textValue' name='textValue' value=''/>
   <script>
     document.getElementById('textValue').setAttribute('value',google.script.run.testGetFieldName());
   </script>
 </body>
</html>

In your script, how about the following modification?

Google Apps Script side:

From:

var html = HtmlService.createTemplateFromFile('index');
var output = html.evaluate()

To:

var html = HtmlService.createTemplateFromFile('index');
html.value = testGetFieldName();
var output = html.evaluate()

HTML side:

From:

document.getElementById('textValue').setAttribute('value',google.script.run.testGetFieldName());

To:

document.getElementById('textValue').setAttribute('value', '<?= value ?>');

Note:

  • If you want to use google.script.run , how about the following modification?

    • From

       document.getElementById('textValue').setAttribute('value',google.script.run.testGetFieldName());
    • To

       google.script.run.withSuccessHandler(e => { document.getElementById('textValue').setAttribute('value', e); }).testGetFieldName();

Reference:

In general, it's a best practice to separate your HTML,CSS,JavaScript files.

References

HtmlService Best Practices

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