克服 gas 可能發生錯誤 code.gs function doGet() { return
HtmlService.createHtmlOutputFromFile("index") } index.html
寶可夢組隊與鋼彈擬人化
以下做法把 「容易在 Google Apps Script (GAS) Web App 出現的三大問題」
一併解掉,並附上 完整、可直接貼上執行 的 code.gs 與 index.html: 常見問題
改善重點 1. 瀏覽器端直接 fetch 需帶 Authorization header,常因 CORS 被擋 →
改由 GAS 伺服端 (UrlFetchApp) 呼叫 xAI,再把 base64 圖片傳回前端 2. 把私密 API
Key 寫在前端 → 暴露 → API Key 存在 Script Properties,伺服端讀取 3.
前端執行大量外網請求,偶爾遇到學校網路或 CSP 封鎖 →
寶可夢資料也可走伺服端,全部透過 google.script.run 無跨域顧慮
① code.gs /** * 首次使用:在 Apps Script 編輯器 → 左側 ⚙️ Project Settings → *
「Script properties」新增 * 名稱:XAI_API_KEY *
值 :xai-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx */ const XAI_KEY =
PropertiesService.getScriptProperties().getProperty('XAI_API_KEY'); /* ===== Web
App 入口 ===== */ function doGet() { return HtmlService
.createTemplateFromFile('index') // 使用範本可嵌入
動態值 .evaluate() .setTitle('寶可夢組隊與鋼彈擬人化')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL); // iframe 友善 }
/* ===== 伺服端呼叫:PokeAPI ===== */ function getPokemonList() { const url =
'https://pokeapi.co/api/v2/pokemon?limit=151'; return
JSON.parse(UrlFetchApp.fetch(url).getContentText()); } function
getPokemonDetails(name) { const url =
`https://pokeapi.co/api/v2/pokemon/${name}`; return
JSON.parse(UrlFetchApp.fetch(url).getContentText()); } /* ===== 伺服端呼叫:xAI
產生鋼彈擬人化 ===== */ function generateGundamImage(pokemonName) { if
(!XAI_KEY) throw new Error('尚未在 Script Properties 設定 XAI_API_KEY !');
const endpoint = 'https://api.x.ai/v1/images/generations'; const prompt = `A
humanoid version of ${pokemonName} wearing a detailed Gundam suit,
photorealistic, transparent background`; const payload = { prompt, n: 1, model:
'grok-2-image-1212' }; const options = { method : 'post', contentType:
'application/json', payload: JSON.stringify(payload), headers: { Authorization:
`Bearer ${XAI_KEY}` }, muteHttpExceptions: true }; const res =
UrlFetchApp.fetch(endpoint, options); const body =
JSON.parse(res.getContentText()); let img64; if (body.images?.[0]?.b64_json) {
img64 = body.images[0].b64_json; } else if (body.data?.[0]?.url) { // 若回傳
URL,再取檔轉 base64 const blob = UrlFetchApp.fetch(body.data[0].url).getBlob();
img64 = Utilities.base64Encode(blob.getBytes()); } else if (body.base64) { img64
= body.base64; } else { throw new Error('xAI 回傳未包含圖片資料'); } return
`data:image/png;base64,${img64}`; } ② index.html html Copy Edit
寶可夢組隊與鋼彈擬人化
③ 部署與測試流程 貼上兩份檔案 App Script 編輯器 → code.gs、index.html 設定 xAI
金鑰 Project Settings → Script Properties → XAI_API_KEY Deploy → New deployment
→ Web app 執行身分:自己.存取權:Anyone 使用網址測試。選寶可夢、點「重繪角色」→
成功看到鋼彈擬人化圖。 這樣即使學校網路或瀏覽器 CSP 封鎖跨域,也能順利呼叫外部
API,避免常見 GAS Web App 的 CORS 與金鑰外洩問題。祝開發順利!