Search code examples
google-apps-scriptweb-applicationstemplate-engine

How to retreive a variable in Javascript HTML file and then map it to a code.gs function


How can I store a variable in Javascript HTML file and then map it to a code.gs function.

Objective:

I want to retrieve var today value from HTML file and then map it to date_preset variable in Code.gs file

I tried doing something like this but it doesn't work:

act_XXXXXX/insights?date_preset=<?!= today; ?> 

Javascript.html

<script>

  var today = document.getElementById('today').value;
  
</script>
    

HTML File

<body>
<div class="block form-group">
  <label for="select">Date Range</label>
  <select id="select">
    <option selected id="today" value="today">Today</option>
   </script>
</div>

<?!= include('Javascript'); ?>

</body>
    

Code.gs

function apiRequest () {

const base = 'https://graph.facebook.com/v10.0/';
  
  const endpoint = 'act_XXXXXX/insights?date_preset=XXX&campaign,impressions,spend;

}
    

Solution

  • You have to listen on the client-side (using JS in your HTML) for when the user selects an option, get the value and send it to code.gs. Using google.script.run you tell the server-side which function to execute. In your case to makes API call with the value you sent.

    Have a read at the client-server communication articles in the documentation.

    Notice how they serve HTML with a <script> which contains a function "google.script.run" which allows to call functions in the server side.

    Example:

    Suppose you are deploying a web app with Apps Script, then:

    // Code.gs
    function doGet() {
      return HtmlService.createHtmlOutputFromFile('Index');
    }
    
    function apiRequest(params) {
      var today = params[0];
      // Your logic here
    }
    

    and:

    <!-- Index.html -->
    <body>
        <div class="block form-group">
            <label for="select">Date Range</label>
            <select id="select">
                <option selected id="today" value="today">Today</option>
            </select>
        </div>
        <script>
        var today = document.getElementById('today').value;
        var account_id = document.getElementById('account_id').value;
        var etc = document.getElementById('etc').value;
        var params = [today,account_id,etc]; 
          google.script.run.apiRequest(params);
        </script>
    </body>
    

    This sends a signal to execute apiRequest(today)