Creating G Suite Add-ons with Apps Script.
I’ve been working on a project to build a G Suite Add-on. This category of software is written in JavaScript and runs within Google’s infrastructure. It’s essentially serverless – you write your scripts, Google runs them, and you don’t think about the compute.
It has it’s own flavor of JavaScript execution environment and a set of APIs for communicating with and extending G-Suite, collectively called Apps Script.
A couple interesting things about it:
- there is conceptually front end and back end code
- the front end is the HTML file(s) that can render a UI that appears in a side bar and runs in an iframe
- the back end are .gs files that run on Google’s infrastructure (JavaScript)
- there is an online script editor – for doing basic stuff – access it from the Tools menu in a google doc, sheet, etc.
- clasp – command line tool for doing local development.
CLASP (Command Line Apps Script Projects) is useful and recommended when you’re ready to “get serious” and not just write simple scripts. It lets you:
- use your preferred text editor or IDE
- keep your code files in a version controlled (Git) repository
- use TypeScript for type checking – ie let the computer help you avoid dumb mistakes
- use a file watcher to upload changes whenever you save – this gives you a faster dev/test iteration loop – save & refresh
- have multiple concurrent deployed versions of a script (haven’t needed this yet)
Interesting things about the Apps Script APIs and execution environment:
- All of the back end .gs files are loaded at once into a single global namespace – no import or require statements.
- Synchronous APIs – most JavaScript node and browser APIs are async, you need to handle how to listen for and respond to callback events or promises. Not so in Apps Script land. You can fetch from an external API (using UrlFetchApp) and the code is synchronous. The next line will not execute until a response is received. Same with getting/saving properties, making changes to spreadsheets, etc. This certainly makes for simpler code.
Maintaining State
In most business applications, you want to maintain some sort of state, such as a user’s auth token to a 3rd party service, their preferences, etc. Any add-on that talks to a 3rd party service might want this. Until today, I was using an additional “Meta” sheet within a Google Sheet to maintain some state. But I thought there must be a better way and found that there is – the Properties service. This lets you store key/value pairs in a few different contexts:
- Script properties – shared among all users of a script, add-on or web app
- User properties – shared only with the current user, for all documents
- Document properties – shared only with the current document, for all users