There's this Q&A: "SpreadsheetApp.getUi() cannot be called from this context"
As you can see, the question is huge, and the answer is correct but incomplete, so both need editing, and the question body needs to be massively edited to help newbies.
Specifically, the error is in the title: SpreadsheetApp.getUi()
cannot be called from this context.
Therefore, the question body could say:
I have this function that works ok if I call it from a google app (like sheets, docs, forms, etc.):
function showDialog(){ var ui = SpreadsheetApp.getUi(); ui.alert("Something"); }
but it triggers error
SpreadsheetApp.getUi()
cannot be called from this context when I run it via script triggers.
How to solve the issue?
This is a common error, and the reason is the .getUi
method got called from places where the UI is not available. As the person who answered said, one example (and most common) is called by time triggered functions, which doesn't have the UI.
Therefore, the correct solution to prevent this failure is to just wrap the call towards the UI in a try catch, or even implement a method like this:
function isUIAvailable(){
try {
SpreadsheetApp.getUi();
return true;
} catch (e) {
return false
}
}
And alert or use the ui only if (isUIAvailable())
.
How should I approach this? Edit both the question and the answer? That seems a bit intrusive, to massively edit it like that.
However, the alternative that I think of doesn't seem right either: re-asking it properly. That is a clear duplicate.