"SpreadsheetApp.getUi() cannot be called from this context" - google-apps-script

In a Google Sheets spreadsheet, I want to show a modal dialog created from HTML, then run a function, then close that HTML prompt automatically.
The dialog should stay until the function finishes executing, then automatically disappear.
This process has to be repeated every 3 hours, and the script needs to run as me (as I have edit permissions that other users do not) so simple triggers probably won't work (I've read that you must create an installable trigger if you want the function to run as you and not whoever the current user is at the given time)
I currently have:
A .gs function Magic_Telling, that creates a modal dialog by using an HTML file
An HTML file, Prompt_Styling, that contains the css / html styling for the prompt. This HTML file then calls a .gs function All_In that processes the rows
My code:
Magic_Telling
Creates the modal dialog from HTML file.
function Magic_Telling() {
var UI = SpreadsheetApp.getUi();
var newline = '\n'
// Display a modal dialog box with custom HtmlService content.
var htmlOutput = HtmlService.createHtmlOutputFromFile('PromptStyling')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(300)
.setHeight(100);
UI.showModalDialog(htmlOutput, ' ');
}
Prompt_Styling HTML file for styling prompt + script that runs the function All_In that will process rows
<html>
<head>
// some irrelevant stuff here
</head>
<script>
window.onload = function() {
google.script.run
.withSuccessHandler(closeDialog)
.All_In();
};
window.closeDialog = function() {
google.script.host.close();
};
</script>
</html>
All_In Function to process rows
function All_In() {
UnlockRowBlocks();
UnhideRowBlocks();
LockRowBlocks();
HideRowBlocks();
}
When I run MagicTelling from the script editor, it works beautifully. The entire sequence executes (prompt shown, All_In executed, prompt disappeared). Perfect.
I then created an installable trigger by going to
Script Editor > Resources > Current project's triggers
and added a trigger to run Magic_Telling every 3 hours.
(I presume this is an "installable trigger")
But I get this error message:
Cannot call SpreadsheetApp.getUi() from this context.
...when the function reaches the first line of Magic_Telling
What should I do to get around this?

Ui Dialogs can not be called by time triggered functions, they have to be triggered by a user action, that's to say a click on a menu item or some sort of button that calls the function showing the UI.

Simple case getting the 'Cannot call SpreadsheetApp.getUi() from this context.'-Error for everybody who just got started with scripting using the Tools > Script editor Menu.
In this case you work with a standalone script only, meaning, your script is just attached to one document or spreadsheet.
The standalone script allows i.e. to simply call doc = DocumentApp.getActiveDocument(), the active Document the script is attached to.
It happened to me that I used var ui = SpreadsheetApp.getUi(); while getting the ERROR message in quest here...
and it took me hours to find out what went wrong with this simple line as I went down all the way to Oauth Scopes and the Developer Console.
So, it might be helpful for some beginners to know that I actually used the var ui = SpreadsheetApp.getUi(); within a Document-Script.
Very clear I got the error, but ...
Hope this is helpful for some simple scripters!
PS. I hope it is needless to mention that using a var ui = DocumentApp.getUi();
within a SpreadSheet will produce a similar Error message.

If this error happened then check the triggers or close the script editor tab and refresh google sheets then open the script project .
Make sure that the Apps Script is bound script and not standalone script . or the getUi() won't work .

If you need to periodically show a message or notification to a user, instead of using a time-driven trigger for calling the Class Ui, use a sidebar and client-side code, i.e. setTimeout in a recursive function, to call a server side function that calls the Class Ui. You might also show the message in the sidebar.
In the case of spreadsheets another option might be use Spreadsheet.toast. Another option is to edit the document. This might work in small documents where the edited section is shown all the time.
When running function calling Class Ui it will fail if the corresponding document editor UI and the Google Apps Script Editor hasn't a connection between an active document, form, slide or spreadsheet and the script.
Time-Driven triggers have a connection with the container / bounded file but there isn't one with the document editor UI, no matter if the script was opened from the document editor UI at the time that the time-driven trigger was executed.
This error will happen too when calling Class Ui from a standalone project because there is no connection with a document editor user interface. While the Google Apps Script editor might look as a "document editor", Class Ui doesn't work with it as the Class Ui can only be called from DocumentApp, FormApp, SlidesApp and the SpreadsheetApp classes.
Below is a simple sample. It adds a custom menu used to open a sidebar. The sidebar holds the client-side code that will open a modal dialog every 10 seconds for 3 times. The client-side code has a timer function that holds a setTimeout which calls the controller function which calls the server-side function and updates a counter used to limit the number of times that the server-side function will be executed.
Steps to use this code:
Create a new spreadsheet
Click Extensions > Apps Script
Remove the default content from default .gs file and add the Code.gs code.
Add two html files and name them sidebar and 'modalDialog.
Add the html sidebar.html and modalDialog.html to the corresponding files.
Run onOpen or reload the spreadsheet and click My Menu > Show sidebar (reloading the spreadsheet will will close the script editor) and authorize the script.
On the spreadsheet, click My Menu > Show sidebar
Code.gs
/**
* Adds a custom menu to show the sidebar
*/
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('My Menu')
.addItem('Show Sidebar', 'showSidebar')
.addToUi()
}
/**
* Shows the sidebar
*/
function showSidebar() {
const myHttpOutput = HtmlService.createHtmlOutputFromFile('sidebar')
.setTitle('My Sidebar')
SpreadsheetApp.getUi().showSidebar(myHttpOutput);
}
/**
* Shows the modal dialog. To be called from client-side code.
*/
function showModalDialog() {
const myHttpOutput = HtmlService.createHtmlOutputFromFile('modalDialog')
.setWidth(400)
.setHeight(150)
SpreadsheetApp.getUi().showModalDialog(myHttpOutput, 'My Modal');
}
sidebar.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<style>
.error {
color : red;
background-color : pink;
border-style : solid;
border-color : red;
}
</style>
<body>
<h1>Timed Modal Dialog Controller</h1>
<div id="sidebar-status">
The modal dialog will be shown after the specifed timeout interval.
</div>
<script>
const defaultInterval = 10000;
let count = 0;
/**
* Run initializations on sidebar load.
*/
(() => {
timer();
})();
/**
* Calls the controller function at the given interval.
*
* #param {Number} interval (optional) Time in ms between polls. Default is 2s (2000ms)
*
*/
function timer(interval) {
interval = interval || defaultInterval;
setTimeout(() => {
controller();
}, interval);
};
/**
* Calls the server side function that uses Class Ui to
* show a modal dialog.
*/
function controller(){
/** Maximum number of iterations */
const max = 3;
if(count < max){
google.script.run
.withSuccessHandler(() => {
const msg = `Counter: ${++count}`;
showStatus(msg);
timer();
})
.withFailureHandler(error => {
const msg = `<div class="error">${error.message}</div>`;
showStatus(msg);
})
.showModalDialog();
} else {
const msg = `<p>Maximum reached.</p>`;
showStatus(msg)
}
}
/**
* Displays the given status message in the sidebar.
*
* #param {String} msg The status message to display.
*/
function showStatus(msg) {
const status = document.querySelector('#sidebar-status');
status.innerHTML = msg;
}
</script>
</body>
</html>
modalDialog.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Attention!</h1>
<p>It's time to take a break.</p>
</body>
</html>
It can be easily adapted to be used on a document, form or presentation.
If the manifest is being edited manually, please be sure to include https://www.googleapis.com/auth/script.container.ui in the list of OAuth scopes besides other required according to the type of document to which the script will be bounded.
If you need to work with a standalone script, instead of a bounded script, you should use it as and Editor add-on.
Reference
https://developers.google.com/apps-script/reference/base/ui
Related
How to poll a Google Doc from an add-on
How do I make a Sidebar display values from cells?
Exception: Cannot call SpreadsheetApp.getUi() from this context. (line 2, file "Code")

Related

Automatically execute Google App Script on Creation of Google Doc or shortly thereafter

We previously had success (from help we've received here!) adding an onOpen menu item that would trigger text formatting. The back story here is that we have google doc merge templates that each have this bound app script. Once the template is generated using data from another source, the user can click the menu item to then format the text. However, as we've grown this has become cumbersome with the number of documents that are generated daily. It requires a user to authorize the script and click the buttons to ultimately format the merged text. This also causes a stopping point in business process because the user running the script is not the ultimate user of the document.
I've pasted the working code below, but I was hopeful that someone might have some ideas on how to change this script so that it ran automatically, without user intervention, after the document is created. The document creation and the data merge happen simultaneously or nearly simultaneously.
function onOpen() {
DocumentApp.getUi().createMenu('Butler')
.addItem('Format Headings', 'FormatHeadings')
.addToUi();
}
function FormatHeadings() {
handle_tags(['<req>', '</req>'], "Roboto", 14, "Bold", "#4a5356");
handle_tags(['<cit>', '</cit>'], "Roboto", 12, "Bold", "#4a5356");
handle_tags(['<con>', '</con>'], "Roboto", 12, "Bold", "#B38F00");
}
function handle_tags(tags, family, size, style, color) {
var body = DocumentApp.getActiveDocument().getBody();
var start_tag = tags[0];
var end_tag = tags[1];
var found = body.findText(start_tag);
while (found) {
var elem = found.getElement();
var start = found.getEndOffsetInclusive();
var end = body.findText(end_tag, found).getStartOffset()-1;
elem.setFontFamily(start, end, family);
elem.setFontSize(start, end, size);
elem.setForegroundColor(start, end, color);
switch (style.toLowerCase()) {
case 'bold': elem.setBold(start, end, true); break;
case 'italic': elem.setItalic(start, end, true); break;
case 'underline': elem.setUnderline(start, end, true); break;
}
found = body.findText(start_tag, found);
}
body.replaceText(start_tag, '');
body.replaceText(end_tag, '');
}
Thank you!
Just to set the right expectations, you can make Apps Script code run by triggering an event or manually running a function. We have those 2 options.
Now, you can't automatically run after the creation of a file because a file creation is not a supported event. You could however:
Create a form that requests the fileID of the new file (the file must be ready to be formatted), use the onSubmit event so when the form is submitted an Apps Script function is executed and the file is created. The onSubmit event is an installable trigger, for more details check the documentation at https://developers.google.com/apps-script/guides/triggers/events#google_forms_events.
You are using DocumentApp.getActiveDocument() you can replace that and use DocumentApp.openById() with the ID that was submitted in the form. This will automatically apply that same script to the file ID you submit in the form.

Execute HtmlOutput code in Google App Script without opening a sidebar

edit: wound up using cheerio to manipulate the elements instead of creating them in a sidebar.
Is it possible to create an execute htmlOutput in a background page, or do so without showing the user anything?
Sample code below:
plugin.gs
function onOpen(e) {
DocumentApp.getUi().createAddonMenu()
.addItem('Start', 'run')
.addToUi();
}
/**
* Opens a sidebar in the document containing the add-on's user interface.
*/
function run() {
var ui = HtmlService.createTemplateFromFile('sidebar').evaluate()
.setTitle(constants.title);
DocumentApp.getUi().showSidebar(ui);
}
sidebar.html
<html>
<head>
<script>
console.log("Hello world!");
</script>
</head>
</html>
This works, but it pops open the sidebar. If I comment out DocumentApp.getUi().showSidebar(ui);, then the page is never created or executed.
Context: I'd like to run some scripts that need to use basic APIs/DOM manipulation like window, document, etc. These don't run on serverside gs files. I want this to happen without having to open a sidebar.

Auto submit google form after a time limit

I want to use app script in my Google form to automatically submit the form in 20 minutes if the user doesn't click on submit within 20 minutes. Anyway to implement this????
No, you cannot control the client-side of Google Forms, even if you add an Apps Script to it, because Apps Script runs on the server.
One possible solution is to serve your form as a Google Apps Script web app. At that point you can write client-side JavaScript and use window.setTimeout to submit the form after 20 minutes.
Here are some example files, Code.gs and quiz.html, that can provide a basic skeleton to start the web app. A blank project will have Code.gs as the default file, then you have to add File > New > HTML file to start the other file.
You can enter the id of any spreadsheet you own in the commented out lines in Code.gs to append the response into that spreadsheet. (You can also automate that process by creating a new spreadsheet as needed. Example of creating spreadsheet to hold data for Apps Script example can be found here.
// file Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile("quiz");
}
function doPost(request) {
if (request.answer) {
console.log(request.answer); // View > Execution transcript to verify this
//var ss = SpreadsheetApp.openById(id).getSheetByName("Quiz Responses");
//ss.appendRow([request.answer /* additional values comma separated here */ ]);
}
}
<!DOCTYPE html>
<!-- file quiz.html -->
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Quiz</h1>
<form>
What is Lorem Ipsum?
<input name="loremipsum" type="text"/>
<button>Submit</button>
</form>
<script>
const button = document.querySelector("button");
const timeLimitMinutes = 1; // low number for demo; change to 20 for application
const timeLimitMilliseconds = timeLimitMinutes * 60 * 1000;
// For this demo we are not going to serve a response page, so don't try to.
button.addEventListener("submit", submitEvent => submitEvent.preventDefault());
// attach our custom submit to both the button and to the timeout
button.addEventListener("click", submitForm)
window.setTimeout(submitForm, timeLimitMilliseconds)
function submitForm() {
button.setAttribute("disabled", true);
document.querySelector("h1").textContent = "Quiz submitted";
// for demo: submitting just a single answer.
// research Apps Script documentation for rules on submitting forms, certain values not allowed
// consider a helper function `makeForm()` that returns a safe object to submit.
const answer = document.querySelector("input").value;
google.script.run.doPost({ answer });
}
</script>
</body>
</html>
Test with Publish > Deploy as web app...

Launching Google Form from App Script

I am trying to launch an Google Form from a script on Google sheets. At the moment, i am doing it trough the form's unique ID and this is what I have:
function addtoDatabase() {
var formaddnew = FormApp.openById('uniqueformID');
}
I am sure i am using the correct form's ID. The script runs without returning any errors or exceptions but the form isn't launched. I am new to App script and I think I might be overlooking something.
Thank you for your help.
You (as me too) were confused with a strange name of function openById:
var formaddnew = FormApp.openById('uniqueformID');
This code does not "open" a form, it assigns a form to the variable formaddnew. You may check it if you add this line of code:
Logger.log(formaddnew);
run the code and press [Ctrl]+[Enter] to see the log.
How to open a form with a script
No. One has no such option because scripts have no access to a browser. A Form is actually opened in a browser, and google-apps-script cannot open new tabs in a browser.
Is there any way though to open a form from a pop-up or message box?
Please try the method described here:
Google Apps Script to open a URL
Here's a tested sample code based on this answer:
var C_URL = 'https://stackoverflow.com/questions/48947678/launching-google-form-from-app-script'; // change
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Menu')
.addItem('Show Window', 'testNew')
.addToUi();
}
function testNew(){
showAnchor('Open this link',C_URL);
}
function showAnchor(name,url) {
var html = '<html><body>'+name+'</body></html>';
var ui = HtmlService.createHtmlOutput(html)
SpreadsheetApp.getUi().showModelessDialog(ui,"demo");
}
Notes:
the script creates a custom menu and opens the window with an URL.
User has to click the URL.

Show authorization popup to editor in sheet Interface instead of running any function manually in google script code editor

I'm working on scripts of google spreadsheet, situation is that a html dialog template would be generated when an edit trigger is triggered.
ScriptApp.newTrigger('onEditSimulation')
.forSpreadsheet(SpreadsheetApp.getActive())
.onEdit()
.create();
And there is a button on the html template, what binding on onclick is :
onclick = "google.script.run
.withSuccessHandler(sended)
.withUserObject(this)
.resendSpreadSheet(<?=newMail?>)
server-side function binding on button would function normally after runs it at code editor and the process of authorization is completed.
The spreadsheet is going to share with other users, but the manner mentioned above is really not friendly and smoothly to my target user, I strongly wanna avoid that. Is there any solution to make authorization popup just show at the sheet Interface?
You could implement a small script that asks the "unauthorized user" to manually run a menu option that would trigger the authorization process.
This function would run only once of course.
Code example below :
function onOpen() {
if(! PropertiesService.getUserProperties().getProperty("authorized")){
SpreadsheetApp.getUi().createMenu('Authorize').addItem('Authorize',authorize).addToUi();
var ui = HtmlService.createTemplateFromFile('index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Authorization request');
SpreadsheetApp.getUi().showModelessDialog(ui,'Authorization request');
}
}
function authorize(){
PropertiesService.getUserProperties().setProperty("authorized", "done");
}
index.html :
<html>
<head>
<base target="_top">
</head>
<body>
Please select the "Authorize " option from the menu<br><br>
<input type="button" value="then close this window"
onclick="google.script.host.close()" />
</body>
</html>