Exception: Cannot call SpreadsheetApp.getUi() from this context. (line 2, file "Code")
Asked Answered
M

3

2

I'm getting this error when I try to run my code to had a custom menu. My code:

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Menu')
      .addItem('Candles','callCandles')
      .addToUi();
}
Matthaus answered 12/12, 2020 at 23:17 Comment(0)
C
2

You are not supposed to manually execute a trigger function. This particular one is activated when you open the spreadsheet.

You can see the menu Candles created on top of the menu bar. You just need to refresh the spreadsheet page and you will see it. Please read carefully the official documentation:

https://developers.google.com/apps-script/guides/triggers

Corrinnecorrival answered 12/12, 2020 at 23:45 Comment(0)
S
0

When running the onOpen trigger or any function calling Class Ui from the Google Apps Script editor, it will fail if the script was opened from a link, from https://script.google.com, etc. but not from the container even if the container was opened later. It might also happen when somehow the document editor UI and the Google Apps Script Editor lost the connection between the active document, form, slide or spreadsheet and the script.

Usually this is fixed by closing the script and open it again from its container. As of September 2022, this is done from the Extensions menu.

Very rarely it might be needed to restart the web browser, and even more rarely it will be required to restart the computer.

Schoenberg answered 17/9, 2022 at 14:31 Comment(0)
S
0

Many thanks to Rubén! After diving deeply into the issue with the normal "DocumentApp.getUi().createMenu('Utilities')" not working error for a few hours I learnt a bit about calling Class Ui, like

  1. the beginner fault to call DocumentApp.getUi() in a Spreadsheet or vice versa,
  2. kind of important message that Ui Dialogs can not be called by time triggered functions.

But I was quite relieved to fix the issue by simply closing the doc and restarting the browser.

The question remains: How can the search for "Cannot open ....getUi() from this context" lead to this solution faster? This could be an AI task to present prioritised, like the solutions from 1. first, then the restart and 2. time trigger functions later.

Sideling answered 22/3, 2023 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.