Apps Script公式リファレンス: Apps Script Reference |障害・課題追跡: IssueTracker |Google Workspace: Status Dashboard

2023年9月21日木曜日

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

Google Slidesで現在選択している表に値を入れたい3 - Insert values into the active table3

Google Slidesで現在選択している表に値を入れたい2 - Insert values into the active table2 上記のリンク先では、値の数に応じて行を追加しました。 In the linked article above, rows were add...