Using Google Sheets with bound Apps Script.
function onOpen(e)
{
// ...tasks that needs "https://www.googleapis.com/auth/script.external_request" scope ...
}
This function fail because onOpen
is a simple trigger and it cannot authorize external_request.
This workaround works:
function onOpen()
{
const ui = SpreadsheetApp.getUi();
ui.createMenu("Authorization")
.addItem("Authorize API Access", "authorize")
.addToUi();
// if task that needs external_request scope fail, alert user to authorize from menu
}
function authorize()
{
UrlFetchApp.fetch("https://www.google.com"); // mocking a request to force auth for external_request
}
Question:
I don't like this workflow. Mocking an arbitrary request makes it not-clean. How to make the workflow cleaner? Perhaps something like this:
function authorize()
{
const scope = "https://www.googleapis.com/auth/script.external_request";
// do something with `scope` to authorize external_request without mocking a request.
}
Use an installable "on open" trigger instead of an onOpen(e)
simple trigger.
Installable triggers are authorized by the user who creates the trigger, and do not need to be authorized by the user at the keyboard. The authorization is given at the time the trigger is created.