Force ask authorization onOpen() (force popup)

Viewed 4875

SUMMARY: Is it possible to ask for authorization onOpen()?

DETAILED VERSION: I have a spreadsheet with buttons that gets distributed to a lot of people. When any button is pressed, some functions that require permissions are called, so Google Apps Script shows this popup:

enter image description here

AFTER this is accepted, everything runs well, since it has authorization now. However, I want to run things that require permissions BEFORE a button is pushed, when the Workbook is opened. However, if you place authorization-requiring code into an onEdit or onOpen function, it runs with no privileges by default and crashes halfway, rather than showing the popup and asking for permissions.

Here is some code that exemplifies this - crashing instead of asking for permissions to create a trigger (also works for CalendarApp, etc.):

function onOpen(e) {
  Browser.msgBox("This is shown to the user");
  try {
    ScriptApp.newTrigger('someFunction').forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet()).onEdit().create();
  }
  catch (e) {
    Browser.msgBox(e);
  }
  Browser.msgBox("This message is never shown to the user if there is no try catch because it crashes");
}
2 Answers

Nowadays it's not always possible to force ask authorization onOpen as Google made some policy changes that now prevent that script automatically open an UI element by using a simple trigger like onOpen.

This could be possible for the owner of the spreadsheet but not for editors.

From my answer (almost one year old, 0 votes so far) to onOpen not executing?

A simple trigger open function can't open a sidebar because it runs on AuthMode.LIMITED. You should use a function that runs on Auth.Mode.FULL to open a sidebar, like an installable trigger.

I know that this isn't about add-ons but the following quote applies

From https://developers.google.com/apps-script/add-ons/lifecycle#authorization_modes

Note: Add-ons can't open sidebars or dialogs while executing in AuthMode.LIMITED. You can use menu items to open sidebars and dialogs since these run in AuthMode.FULL.

The cannonical references are

Related