GAS Web Apps 網頁應用程式
Google Apps Script 可以將你的程式碼轉換為一個具有公開 URL 的網頁。這讓你能夠建立自定義的表單、Dashboard,或是對外開放的 API 介面。
核心函數:doGet 與 doPost
Web App 有兩個固定的入口函數,分別對應 HTTP 的 GET 與 POST 請求。
/**
* 處理網頁瀏覽 (GET) 請求
* @return {HtmlOutput} 回傳網頁內容
*/
function doGet(e) {
// 建立 HTML 模板
const template = HtmlService.createTemplateFromFile('Index');
// 注入變數到前端
template.username = '訪客';
return template.evaluate()
.setTitle('我的 GAS 網頁')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
/**
* 處理資料送出 (POST) 請求
*/
function doPost(e) {
const data = JSON.parse(e.postData.contents);
console.log('收到資料:', data);
return ContentService.createTextOutput(JSON.stringify({result: 'success'}))
.setMimeType(ContentService.MimeType.JSON);
}
HtmlService:前端介面設計
你可以建立一個 .html 檔案(例如 Index.html),並在裡面寫標準的 HTML / CSS / JS。
如何在 HTML 中與後端互動?
前端 JS 使用 google.script.run 來呼叫後端的 GAS 函數。
<!-- Index.html -->
<h1>Hello, <?= username ?></h1>
<button onclick="handleSubmit()">送出資料</button>
<script>
function handleSubmit() {
const info = { name: "Mike", score: 100 };
// 呼叫後端函數 processData
google.script.run
.withSuccessHandler(res => alert('伺服器回傳:' + res))
.processData(info);
}
</script>
核心 Web App 函數語法說明
HtmlService 相關
- HtmlService.createTemplateFromFile(filename):從指定的 HTML 檔案建立模板。
- template.evaluate():解析並執行模板中的腳本代碼(
<? ... ?>),回傳HtmlOutput。 - setTitle(title):設定瀏覽器標籤頁的標題。
- setXFrameOptionsMode(mode):設定是否允許被嵌入(iframe)到其他網站。
部署權限設定 (Deploy)
當你點擊「部署」為 Web App 時,有兩個關鍵選項:
- 執行為 (Execute as):
我(Me):網頁會以你的權限執行(可存取你的 Drive/Sheets)。訪問網頁的使用者:以使用者的 Google 帳號權限執行。
- 誰有權限存取 (Who has access):
僅限我本身。任何擁有 Google 帳戶的使用者。任何人(Anonymous):適合做公開 API 或免登入表單。
分離 CSS 與 JavaScript
為了保持程式碼整潔,建議將 CSS 與 JS 分開寫。
/**
* 輔助函數:將外部檔案內容包進 HTML
*/
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
在 Index.html 中引用:
<style>
<?!= include('Style.css'); ?>
</style>
<script>
<?!= include('JavaScript.html'); ?>
</script>
<?!= ... ?> 是強制不轉義輸出,用於直接嵌入程式碼或樣式。