Zhang Quan
Zhang Quan

Reputation: 77

Render changes in server-side variable on client-side in Google Apps Script

I'm currently trying to have a variable on the server side, and a function to update the value when a user clicks on a button (e.g. similar to React's setState). In my code.gs I have this:

var masterText = "Hello";
function changeText(text){
   masterTextext = text;
}

On my client-side, I have Index.html which is meant to display the value, and when the user clicks on any of the buttons, the text will change:

<script>
    function changeText(text) {
        google.script.run.changeText(text)
    }
</script>
<?= masterText ?>
<button class="navbar-button" onClick="changeText('HI')">Leaderboard</button>
<button class="navbar-button" onClick="changeState(2)">Videos</button>

However, when I try to execute this, the value in <?= masterText ?> doesn't change on the client-side and it remains as "Hello". How do I fix this?

Upvotes: 1

Views: 795

Answers (1)

Muhammet Yunus
Muhammet Yunus

Reputation: 589

We can't use global variables in server side, but User Properties instead.

You can store masterText as a user property, and call it from client side.

Here I've prepared for you a sample. Here is the codes.

Server side:

function doGet() {
  
  return HtmlService.createTemplateFromFile('index').evaluate()
  
}

function changeProperty(text){
  UserProperties.setProperty('masterText',text)
}

function getMasterText () {
  return UserProperties.getProperty('masterText')
}

Client side:

<html>
  <head>
    <base target="_top">
    <style>
      #textDiv {
        height: 100px;
        padding : 25px
      } 

      span {
        color : red
      }
    </style>
  </head>
  
  <body>
    <input id="input1">
    <button onClick="changeProperty(input1.value)">Change</button>

    <div id="textDiv">
      Master Text : <span id="textSpan"><?!= getMasterText () ?></span>
    </div>

    <script>
      function changeProperty(text) {
        google.script.run.withSuccessHandler(getMasterText).changeProperty(text)
      }

      function getMasterText () {
        google.script.run.withSuccessHandler(function (response) {
          textSpan.innerHTML = response
        }).getMasterText()
      }
    </script>
       
  </body>
</html>

Upvotes: 1

Related Questions