LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Thursday, September 21, 2023

A simple application using google.script.run


Introduction

I will introduce a simple application that uses Google Apps Script and google.script.run to display a message with the user's name. 

The application places a text box and a button on the screen. 
When the button is clicked, the name entered in the text box is passed to a server-side Apps Script function, which returns a message with the user's name. 
The message is then displayed on the screen.

I will also explain how to use the google.script.run API to call server-side Apps Script functions from client-side JavaScript. 
The google.script.run API allows you to pass arguments to the server-side functions and to receive results back from them.


Application

A text box and a button on the screen



Enter your name and click the button, a message will be displayed on the screen.


Source Code

Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index').setTitle("Title");
}

function returnHello(name) {
return "Hello" + " " + name;
}


index.html
<!DOCTYPE html>
<html>
<body>
<input type="text" id="name">
<button id="bt">submit</button>
<script>
document.getElementById("bt").onclick = runHello;

function runHello() {
var name = document.getElementById("name").value;
google.script.run
.withFailureHandler(onFailure)
.withSuccessHandler(onSuccess)
.withUserObject("how are you?")
.returnHello(name);
}

function onSuccess(result, userObject) {
alert(result + " " + userObject);
}

function onFailure(e) {
alert([e.message, e.stack]);
}
</script>
</body>
</html>



Tips

google.script.run
call server-side Apps Script functions(in Code.gs)

.withFailureHandler(function)
a callback function to run if the server-side function throws an exception

.withSuccessHandler(function)
a callback function to run if the server-side function returns successfully

.withUserObject(object)
a second parameter to the success and failure handlers
        
.returnHello(name)
run a function in Code.gs


Reference

Class google.script.run (Client-side API)

Latest post

スプレッドシートA列にある複数のテキストをスライドに追加したい(Google Apps Script)

今回Google Apps Scriptでやりたいこと GoogleスプレッドシートA列にある複数の値を取得して Googleスライドに渡して 図形オブジェクトのテキストとして追加したい ① スプレッドシートのA列に値を入れておく ② Code.gsのinsertNewShape...