One of the most powerful aspects of using HTML Service in Google Apps Script is the ability to create dynamic web applications where the client-side (HTML, JavaScript running in the browser) and the server-side (your Apps Script code) can communicate with each other. This bidirectional communication allows you to fetch data from Google services, process it on the server, and then display it dynamically in your web app, or conversely, capture user input from the web app and use it to perform actions on the server.
Google Apps Script provides two primary methods for this communication: google.script.run for server-to-client calls and google.script.submit for client-to-server calls. Let's break down how each of these works.
Client-to-Server Communication: google.script.run
When your user interacts with your HTML Service web app (e.g., clicks a button, enters text), you often need to send that information to your Apps Script code running on Google's servers for processing. The google.script.run object, available in the client-side JavaScript of your HTML Service template, is your gateway to calling server-side Apps Script functions.
function sendDataToServer() {
var userInput = document.getElementById('myInput').value;
google.script.run.processUserInput(userInput);
}
// Attach this function to a button's onclick event in your HTMLIn this example, sendDataToServer is a client-side JavaScript function. When called, it reads a value from an input field and then uses google.script.run.processUserInput(userInput) to invoke a server-side function named processUserInput, passing the userInput as an argument. The processUserInput function must be defined in your Apps Script's .gs file.
function processUserInput(input) {
Logger.log('Received from client: ' + input);
// Perform server-side operations here, e.g., save to a Sheet
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().appendRow([input]);
return 'Data processed successfully!';
}Notice that the server-side function processUserInput can also return a value. This return value can be asynchronously handled back on the client-side, allowing for feedback or further client-side actions based on the server's response.