如果是從文件(容器)建立Google Apps Script,可以用一些特別的觸發器或者方法
因為最剛開始的程式碼是直接從 Google Apps Script建立新專案
透過SpreadsheetApp.openById()連結目標工作表
但是現在為了更方便執行程式,想在試算表(文件)建立功能選單
而這就必須要讓文件(容器)能夠執行別的專案程式

想說除了搬動程式碼之外,是否有其他方法
於是用「如何由A專案執行B專案的程式」為關鍵字來搜尋
透過在A專案使用UrlFetchApp.fetch方法來執行B專案的程式碼
當然B專案的程式碼就要部署成網頁應用程式,並且將程式碼搬動到 doPost內,或者直接在doPost內呼叫程式
不過這篇文章其實是發問者遇到權限問題來尋求解決方式
有人回答他
Please add the // DriveApp.getFiles() of the comment line.
This comment line is used for automatically detecting the scope.
In this case, https://www.googleapis.com/auth/drive.readonly is added to the scopes.
If this didn't resolve your issue, please add the comment line of // DriveApp.createFile(blob).
In this case, https://www.googleapis.com/auth/drive is added.
也有類似的解決方式
差別是在直接在專案的設定中加入所需要的授權範圍
這個就需要知道程式碼需要的授權範圍,要回去看Google的說明文件
不過大致都需要以下這兩種授權
"https://www.googleapis.com/auth/script.external_request",可以查詢外部資源
"https://www.googleapis.com/auth/drive",可以存取雲端資料夾內的檔案
但如果在部署設定的「誰可以存取」設置為"所有人"就不需要額外設定授權範圍了


清楚方法之後就是修改程式碼
首先增加doPost函式
#2 在函式內呼叫原來的程式getDatafromSheet()
#3 程式執行完畢回傳"good",基於安全考量要透過ContentService.createTextOutput()來處理回傳的字串
1 2 3 4 |
function doPost() { getDatafromSheet(); return ContentService.createTextOutput("good"); } |
再將程式碼發布成網頁應用程式 ,取得網頁應用程式連結

接著在原來的文件(容器)建立Apps Script,加入以下程式碼
#1 onOpen觸發器
#2-6 設定選單,執行moveReurest()
#9-17 moveReurest()的內容
#11-13 是必須的,如果沒有加入OAuthToken,爬文到的資訊是說會收到403 Forbidden錯誤訊息
#14 webAppUrl是前面取得的網頁應用程式網址
#15 接收回傳值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function onOpen() { var ui = SpreadsheetApp.getUi(); // Or DocumentApp, SlidesApp or FormApp. ui.createMenu('Custom Menu') .addItem('getDatafromSheet', 'moveReurest') .addToUi(); } function moveReurest(){ //移動副本文件到特定資料夾_doPost var auth = ScriptApp.getOAuthToken(); var header = { 'Authorization': 'Bearer ' + auth }; var options = { 'method': 'post', 'headers': header }; var webAppUrl = "https://script.google.com/macros/s/*************************************/exec"; var msg =UrlFetchApp.fetch(webAppUrl,options); Logger.log(msg); } |

加入授權範圍

這樣就可以從工作表的自訂功能選單執行另一個專案的程式了



從專案的執行紀錄也可以確認程式有被呼叫
文件(容器)選單執行moveReurest(),fetch 另一個專案所發布的網頁應用程式
doPost()被觸發執行getDatafromSheet(),完成之後回傳"good"到moveReurest()的msg


0 comments:
張貼留言