I have been stuck here with this error for the past 3 hours.
Error Exception: Cannot call SpreadsheetApp.getUi() from this context.
I would appreciate the help.
function onOpen(e) {
var menu = SpreadsheetApp.getUi().createMenu("Refresh");//The error is here
menu.addItem("Refresh Week", "menu");
menu.addToUi();
}
//The same thing goes to this function as well
function menu(){
//get the good week number
var date = new Date();
var wn = [(Math.floor(WEEKNUMBER(date))+3).toFixed(0)]
do {
wn.push((wn[wn.length-1]-1).toFixed(0))
} while(wn[wn.length-1] != 348);
var line = "<select style='width:60px;height:40px;' id='select'>"
for ( var x in wn )
line +="<option>" + wn[x] + "</option>"
line +="</select>"
var ui = SpreadsheetApp.getUi();
var html = HtmlService.createHtmlOutputFromFile('Selector')
.setWidth(200)
.setHeight(150).setContent("<div>"+line + "</div><br><div><button onclick='reset()'>Confirm</button></div><script>function reset(){var wn = document.getElementById('select').value;document.getElementsByTagName('Body')[0].style.cursor = 'wait';google.script.run.withSuccessHandler(function (){google.script.host.close();}).readWP2(wn);}</script>")
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'Please select a week number');
}
So when I create a variable and set it to SpreadsheetApp.getUi()
I start getting this error and the rest of the code just doesn't run anymore because of this error
I'm using Google Apps Script.
I believe what you are trying to do is to create a dialog box that is similar to JavaScript Popup Boxes. Unfortunately, Apps Script does not have that feature. You need to bind it first to Google Sheets, Docs, Slides, or Forms file and the dialog box will appear on those apps.
I was able to replicate your issue by executing your code on a standalone script. A standalone script is any script that is not bound to a Google Sheets, Docs, Slides, or Forms file or Google Sites.
Standalone example:
SpreadsheetApp.getUi();
only interact with the UI for the current instance of an open spreadsheet, and only if the script is bound to the spreadsheet.
To solve your issue, make sure to:
Your code should work on either Spreadsheet Menu or in Apps Script but the dialog box will always show on Spreadsheet.
References
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With