星期日, 8月 03, 2025

[GAS] ScriptApp.getService().getUrl()

[GAS] HTMLService 練習時,最大困惱莫過於每次重新佈署後,都必須至 index.html 內手動替換掉 form action url,該 url 變成是一種 HardCode 狀態,查詢資料發現,可以在 .gs 檔案內透過 ScriptApp.getService().getUrl() 來取得部屬後的 url

.gs 檔案

透過 ScriptApp.getService().getUrl() 取得 url 後,可以使用方法一,把 url 當成參數塞進 index.html 去,如同上篇筆記傳遞參數做法,該筆記是改採方法二,設定一個 GetUrl()
function doGet(e) {
    let htmloutput = HtmlService.createTemplateFromFile('index')
    htmloutput.date = Date();
    
    // 方法一:當成變數塞進去
    // htmloutput.url = ScriptApp.getService().getUrl();
    // Logger.log(htmloutput.url);

    return htmloutput.evaluate();
}

function doPost(e) {
  return Activity(e);
}

// 方法二:建立 GetUrl()
function GetUrl() {
  let url = ScriptApp.getService().getUrl();
  Logger.log(url);
  return url;
}

function Activity(e) {
  let spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  let sheet = spreadSheet.getSheetByName("工作表1");
  let data = [e.parameter.email , e.parameter.date , e.parameter.meal , e.parameter.note];
  sheet.appendRow(data);
}
index.html

form action 內直接使用 .gs GetUrl() 來取的部屬後 url
<!DOCTYPE html>
<html>

<head>
  <base target="_top">
</head>

<p>目前時間:<br>
  <?= date ?>!
</p>

<body>
  <!-- action 內直接設定使用 .gs GetUrl() -->
  <form
    action="<?= GetUrl() ?>"
    method="POST">

    <label for="email">Email:</label><br>
    <input type="email" id="email" name="email" size="30"><br><br>

    <label for="date">報名活動日期:</label><br>
    <input type="date" id="date" name="date" size="30" style="width:228px"><br><br>

    <label for="meal">餐點:</label><br>
    <select id="meal" name="meal" style="width:228px">
    <option value="meat">葷</option>
    <option value="vegetarian">素</option>
  </select><br><br>

    <label for="note">備註:</label><br>
    <textarea id="note" name="note" rows="4" cols="30"></textarea><br><br>

    <button type="submit" style="width:228px">送出</button>
  </form>
</body>

</html>
執行結果

因為 GetUrl() 內有使用 Logger.log 輸出,可以在執行項目找到,對應部屬 url 是一致的

學習 ScriptApp.getService().getUrl() 時,發現不少人反應有 bug,目前測試是沒有遇上,先紀錄相關文章就是

沒有留言:

張貼留言