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

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ドキュメントに見出しを追加したい

今回の例では、ドキュメントの末尾に「見出しD」 を追加します。 見出しA, B, C, Dのスタイルは、見出し3 ( HEADING3 ) に設定しています。  下記Code.gsの  GOOGLE_DOCUMENT_URL を設定して  addHeadingToEnd()  を...