Launching Google Form from App Script - google-apps-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.

Related

User haven't permissions for calling showModalDialog()

In Google Sheets I use this code for opening a URL after a user edits some cell, but there is problem: I can open the URL in a modal window, but other editors cannot. When I review the Stackdriver logs, I see errors that state the script does not have permission to call showModalDialog().
function onEditTrigger(e) {
var eRange = SpreadsheetApp.getActiveSpreadsheet().getActive().getActiveRange();
var eRow = eRange.getRow();
var eCol = eRange.getColumn();
if (eCol == 1)
openUrl("https://stackoverflow.com");
}
function openUrl(url) {
var html = "<script>window.open('" + url + "'); google.script.host.close();</script>";
var userInterface = HtmlService.createHtmlOutput(html).setHeight(6).setWidth(9);
SpreadsheetApp.getUi().showModalDialog(userInterface, 'Opening ...');
}
I have installed an "edit" trigger for the "onEditTrigger" function. How can I make sure it works for all editors?
You can't have your script executing JS code snippets simply by sharing it with other users. Your collaborators will still need to open the Script Editor and manually re-authorize the bound script. Sure thing, Google will throw the usual warnings at them while they do it.
The OnEditTrigger will still fire but injecting client-side code will result in failure.
JS code can be used for malicious purposes and stealing private data, so I don't think Google will allow anyone to avoid the explicit authorization flow.

Doesn't work - Cross-domain Redirect in google form in an iframe in google sheets app script

I have a function launchForm within a Google Sheet which calls another function createForm with a single question. I get the URL of the newly created form and pass it into a sandbox Iframe using UrlFetchApp, as shown below:
function launchForm() {
var form = createForm(); // separate function that works fine
formUrl = form.getPublishedUrl()
var response = UrlFetchApp.fetch(formUrl,{"followRedirects" : true}); // true if automatic redirecting works
var formHtml = response.getContentText();
var htmlApp = HtmlService
.createHtmlOutput(formHtml)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL) // did this to prevent error but didn't help
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.show(htmlApp);
}
I have created a custom menu in sheets to run the launchForm function.
The trouble is, that the new form URL is at docs.google.com/a/, while the sheet is at docs.google.com/spreadsheets/d/...
This means that the iframe, instead of loading the form, opens up to a sign-in screen in when I (the creator of the form) tries to run it. When someone else with edit permissions runs the script, he sees the form as expected, but is then unable to make any inputs into the form.
I have read about CORS, X-frame-options, OAuth2, and nothing seems to provide the precise answer about what I must do. Any help will be much appreciated.

"SpreadsheetApp.getUi() cannot be called from this context"

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")

modal dialog with new spreadsheet api issue

I'm was trying to show html body of gmail message in modal dialog window but faced an error calling SpreadsheetApp.getUi() method.
...
var html = HtmlService.createHtmlOutput(threads[i].getMessages()[0].getBody());
SpreadsheetApp.getUi().showModalDialog(html, 'My add-on');
...
How I can call that dialog? Or may be there is better aproach to display message(some panel or sidebar)?
This prompt box is misleading, as the error must be elsewhere. The new version of Sheets not only does support the getUI method, I believe it's specifically designed for for the new version of sheets.
I've expanded on your previous question and tested this myself with the following code in the new version of sheets:
function getMail() {
var threads = GmailApp.getInboxThreads();
var messages = threads[0].getMessages()[0];
var raw = messages.getPlainBody();
return raw;
}
function dialogueBox(){
var raw = getMail();
var htmlOutput = HtmlService.createHtmlOutput(raw);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'For mk_yo');
}
and it displays the prompt with no issues, as shown here. Try creating a new sheet with a new script and run the code above. Additionally, you can try ensuring that the sheet that you're adding this to is definitely using the new version of sheets.
In relation to if there's a better approach by displaying a side panel, yes you can use custom sidebars in the new version of Google sheets(and only the new version), but as this still uses the 'getUI' method, this won't resolve your current error, as this is not where the issue lies.

DialogBox in addon for Google Form

I'm trying to display a DialogBox from a function used in an addon for Google Form.
function onOpen() {
FormApp.getUi()
.createMenu('MyAddon')
.addItem('Test', 'myTest')
.addToUi();
}
function myTest() {
Logger.log("--> called");
var app = UiApp.createApplication(); // or UiApp.getActiveApplication()
var dialog = app.createDialogBox();
dialog.setPopupPosition(100, 100).setSize(500, 500);
dialog.show();
return app;
}
Unlike FormApp.getUi().showModalDialog(content, title), function using DialogBox is called but does nothing (nothing is displayed).
Does anyone succeed in displaying such component in a Google addon?
Goal of using DialogBox is to be able to set a close handler, which is not possible using .showModalDialog(...) (which returns void but not reference to created dialog).
I don't see any other way in Google API for UI in addon to display a dialog, with a callback when it's closed.
Calling this function from server side code (which is what happens when that menu item is selected) will not display this Ui if it is just returned from the function. You need to use a method such as SpreadsheetApp.getUi().showModalDialog(uiInstance, 'My add-on'); to have it display for the user.
If all you're looking for is a way to take action once the dialog is closed, consider using alert dialogs or prompt dialogs. These will return an object which can be queried to see which button the user selected, or what text was entered in the dialog.