Execute HtmlOutput code in Google App Script without opening a sidebar - google-apps-script

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.

Related

Bookmarklet hosted in Apps Script unable to run when shared

After deploying my web app in Apps Script with bookmarklet, it works fine on my end however not when I tried to share my web app, it throws an 'unsafe javascript' error like its being clicked from the web app and not as a bookmarklet.
The web app is run as user accessing and can be accessed by anyone in our organization.
What bookmarklet does is run a prompt for input and find it on the current page.
The code goes like this:
<a id="bkmark">Link</a>
<script>
document.body.onload=()=>{
google.script.run.withSuccessHandler(rep).getLink();
function rep(e){
document.querySelector('#bkmark').href = e; // return a javascript: IIFE wrapped in ``
}
}
</script>
And my gs returns Html output from a file.
Any help appreciated, Thanks!
Instead of adding the JavaScript as a booklet, you can directly import using ContentService and templates:
Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="<?= ScriptApp.getService().getUrl() + '?getAction=true' ?>" type="text/javascript" defer async></script>
</head>
<body>
<button id="trigger" onclick="doAction()" disabled>Click here to do something</button>
</body>
</html>
Code.js
function doGet(e) {
const { getAction } = e.parameter
if (getAction !== undefined) {
return genAction()
}
return HtmlService.createTemplateFromFile('Page').evaluate().setTitle("Booklet webapp")
}
function genAction() {
return ContentService
.createTextOutput(`
function doAction() {
alert("Hello world!")
}
(function loaded() {
document.getElementById("trigger").disabled = false
})();
`)
.setMimeType(ContentService.MimeType.JAVASCRIPT)
}
Notice that the script tag has defer and async. This makes it so the script doesn't start loading after the DOM has been fully loaded and it starts doing so asynchronously (without blocking the main thread).
On the Apps Script side, we use a template so we can dynamically get the script execution URL (with ScriptApp.getService().getUrl()) and we add a query parameter (getAction) so we can detect it on the doGet(e) function. There we check for that parameter and we have it we return a JavaScript content instead.
Also made the button disabled by default and I added a small code so the button get enabled when the script has finished loading (it's asynchronous so it can take some time to fully load).
This technique can also be used to dynamically add an script tag by fetching the result, creating the script element, and adding the contents manually.
References
Class ContentService (Google Apps Script reference)
Class HtmlTemplate (Google Apps Script reference)
HTML Service: Templated HTML (Google Apps Script guides)
HtmlService.createTemplateFromFile(filename) (Google Apps Script reference)
Service.getUrl() (Google Apps Script reference)

Google Script pulling dynamic HTML iFrame from Google Sheet Cell

I am working on a incorporating a Google Form as an iFrame in a Modal Dialog box on my Google Spreadsheet (it is already accessible through a customer menu) with iFrame code that dynamically changes based on what's going on in the spreadsheet.
My Google Script to reference the HTML file is:
//Help Guide
function openHelp() {
var html = HtmlService.createHtmlOutputFromFile('Help Guide').setHeight(560).setWidth(814.81).setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi().showModalDialog(html, ' ');
}
When I paste the generated iFrame code into the HTML file 'Help Guide', it loads as desired. However, I would like to instead reference my iFrame code that is housed on Sheet1!C1 when I run the openHelp() function from the menu. This would enable me to dynamically change the iFrame based on the spreadsheet. I have explored using Google's HTML Template service, but haven't been able to figure it out.
I am sure the script is quite easy, but I am unfamiliar with what code needs to be written in the HTML file to pull that generated iFrame code from Sheet1!C1.
Thanks!
Get some HTML code from a Cell in a Spreadsheet
You need to update the variables iframeSheet and iframeCell.
Create the iframe statement.
Deploy as a web app. The doGet is already there. You can also run the showIframeDialog() function to see it work.
The Code:
function getIframeCode()
{
var iframeSheet='Sheet1';
var iframeCell='A1';
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(iframeSheet);
var hl=sh.getRange(iframeCell).getValue();
return hl;
}
function showIframeDialog()
{
var ui=HtmlService.createHtmlOutputFromFile('iframecode');
SpreadsheetApp.getUi().showModelessDialog(ui, 'Dynamic Iframe')
}
function doGet()
{
var ui=HtmlService.createHtmlOutputFromFile('iframecode');
return ui.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
The iframecode.html file:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
google.script.run
.withSuccessHandler(updateIframeCode)
.getIframeCode();
});
function updateIframeCode(hl)
{
document.getElementById("iframe").innerHTML=hl;
}
console.log("My code");
</script>
</head>
<body>
<div id="iframe"></div>
</body>
</html>

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>

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

Run a Google apps script automatically upon loading a Google Site?

I wrote an Apps Script that takes a spreadsheet and converts it into a Google form. I want to display the form on my google site; however, I want the form to automatically refresh every time the site is opened, so that if the spreadsheet has changed, the form will also be updated when it displays. Essentially, I want the script to run automatically upon open of the Google site – any idea how to do this?
Also, as a side note (not as important), is there any way to incorporate a script into a google site without displaying it as a gadget? I don't want to display the script, I just want it to run in the background.
You can run an Apps Script function indirectly when the site loads by creating a stand alone Web App with HTML Service, publishing it, and putting window.onload into a script tag:
<script>
window.onload = function() {
console.log('Onload ran. ');//Open the browser console log to see debug messages
};
</script>
Then use google.script.run to run a server function:
<script>
window.onload = function() {
console.log('hah! it ran. ');
google.script.run
.withSuccessHandler(run_This_On_Success)
.gsServerFunction();
};
window.run_This_On_Success = function(the_Return) {
console.log('was successful!: ' + the_Return);
};
Code.gs
function gsServerFunction() {
return true;
};
index.html
<!DOCTYPE html>
<html>
<body>
This is the body
<script>
window.onload = function() {
console.log('hah! it ran. ');
google.script.run
.withSuccessHandler(wuzSugzezvul)
.gsServerFunction();
};
window.wuzSugzezvul = function() {
console.log('was successful!');
};
</script>
</body>
</html>
Remove the border and the title of the apps script gadget, make it very small, and don't put in any text to display in the HTML.