Working with App Script for Google Workspace
Introduction
Google Workspace is a set of productivity tools like Gmail, Google Sheets, Docs, Calendar, Drive, Sheets. These tools can be used collectively for achieving many productivity tasks and this is where App Script comes in the picture.
App Script is a cloud-based JavaScript extension by Google that extends and automates tasks performed with these G-Workspace tools. It allows you to write simple scripts to handle repetitive tasks and streamline workflow among Google Workspace apps.
It is used to automate routine tasks, build custom add-ons for Workspace apps and seamlessly connect to external APIs and automation tools like Zapier.
In this article, I will be guiding you on how to use this G-Workspace automation tool on some Google Workspace tools.
I will be using practical script examples to show you how to use and troubleshoot App Script.
Getting Started with Google Apps Script: The Interface
App Script is enabled by default on all Google Workspace platforms, so you won’t be needing to install it from the Chrome Web Store.
Editor
This is where you write and edit scripts.
Triggers
Triggers allow you to schedule automatic actions from App Script.
I will come to the point of creating new triggers later.
Executions
This allows you to monitor all the scripts you have worked on and view any debug errors. It is basically like your dashboard.
Services
This allows you to integrate external APIs with App Script. If you scroll down, you can see all other tools that can be integrated with App Script.
Google Docs
Write a Document
Open up your Google Docs by typing on your browser; docs.google.com
Click on Extensions > Apps Script.
- The script editor opens in a new tab, where you can start coding.
Here is an example of a script you can write:
function helloWorld() {
DocumentApp.getActiveDocument().getBody().appendParagraph('Hello, World!');
}
To run the code, ensure you save it first. When you click run for the first time, it may seek your permission, grant it by selecting the Google account you wish to associate with your scripts.
When you click on ‘Review Permission’, there is a possibility that you will get an error when it tries giving access.
The error page you will see would look like this:
If you encounter such an error, click on ‘Advanced’, clicking on it will reveal another message that will prompt you to continue past the safety check.
Click on ‘Go to docs script(unsafe) and continue. This will open the Google Oauth page. Click on allow to continue through your script.
This is a one off process, so you won’t have to repeat it anytime you want to run a script on this document.
Now, run your script and it will automatically append the text, ‘Hello World!’ to the body of your currently active google docs. App script will break down the execution processes for you just like it did here.
Adding and Formatting Headers and Footers
Using App Script, I can create a header and footer with text on my document. Here is a script to add them at once
function addHeaderAndFooter() {
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();
// Add a header at the top
const header = doc.addHeader();
header.appendParagraph("Document Header");
// Add footer content
const footer = doc.addFooter();
footer.appendParagraph("Sample Footer");
}
Insert Images from URLs
Here is a sample script that can let us fetch an image from its web URL and embed it into our document.
function insertImage() {
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();
const imageUrl = 'https://c76c7bbc41.mjedge.net/wp-content/uploads/tc/2022/04/Untitled-design-7.png'; // Replace with your preferred URL
const blob = UrlFetchApp.fetch(imageUrl).getBlob();
body.appendImage(blob);
}
Here, I used a URL from techcabal, you can replace it with yours or try mine.
Running the script will add the image to your document.
Note: App Script cannot access images from your local storage. But if you need to work with such, you would have to upload the image to your Google Drive, then reference from there.
Merging Multiple Google Docs
One cool feature I love about working with App Script on Google Docs is that it allows me to merge many documents togther. Here is a script I made for it.
function mergeDocs() {
const docIds = [
'1VkNXSU2udcV13ShnvsVEDBPGir5U6q0XIhpDIOh44aI',
'19ejeY33KwLLfHeVaDMuNSUym2iJTuoZtF-SzcOBkonM'
];
const mergedDoc = DocumentApp.create('Merged Document');
const mergedBody = mergedDoc.getBody();
docIds.forEach((id, index) => {
try {
const doc = DocumentApp.openById(id);
const body = doc.getBody();
mergedBody.appendParagraph(body.getText());
if (index < docIds.length - 1) {
mergedBody.appendPageBreak();
}
} catch (e) {
Logger.log(`Failed to process document ID: ${id} - ${e.message}`);
}
});
Logger.log(`Merged document created: ${mergedDoc.getUrl()}`);
}
For this to work, you must use the document IDs and not the entire document’s URL. Secondly, you must have all the documents open on your browser’s tab.
The highlighted part of the URL is how to get the document ID of a google document.
You could also use App Script to work with emails. In this example, I am going to show you how you can use App Script to convert a google docs to an email. Let’s get with the script.
Note: Since we are working with emails, there will be inputs for placeholders, I am going to hide the sensitive info, but in your script, be sure to change them and add a real name/email/title.
Also, you are going to be prompted to grant the app access to your Google account, grant it.
Running the script will send an email to the email address you inputted, and send you a message that your task has been executed successfully.
The areas I highlighted with my arrows are placeholders you need to edit.
Here is the sample script to modify: function sendEmailFromGoogleDoc() {
// Document ID of the Google Docs document you want to use
const docId = '1SrP02ixxxxxSaaJBxxxxxxx4BLDShEkS0fUIwrAJo';
// Open the document by ID
const doc = DocumentApp.openById(docId);
// Get the document body
const body = doc.getBody().getText();
// Email parameters
const recipient = example@email.com'; // The recipient's email address
const subject = 'App Script Test'; // The subject of the email
// Send the email with the document content as the body
MailApp.sendEmail({
to: recipient,
subject: subject,
body: body
});
Logger.log('Email sent successfully!');
}
Here is an image of my email from App Script:
Triggers in App Script
Triggers are part of App Script’s automation that runs when certain criteria is fufiled, they don’t require a special script to be written on their behalf. Just specify the parameters and your prefered action.
Here is an example of Trigger in App Script
What this trigger does is that it inserts an image in a specific Google Doc that is linked to your script each time the document is opened.
So, already, you have written a script that takes an image from wherever it is and automatically inserts it into this doc(already referenced by its ID in the script.)
Best Practices for Apps Script Development
App script is cool, but there are certain things you need to get right to ensure that your script runs as intended. The script’s syntax is one thing, understanding these things is another.
Quota Limit: App script has quota limits. When I begun using App Scripts initially, I was not aware of this until my scripts began to have execution problems even when my syntax was correct. It was then that I researched and found out that Google places a limit on how many times your script can be executed in a day, after that, script execution begins to malfunction even if on the execution log, it shows that everything is okay.
This may be a bit problematic as you have to run your script to discover errors in it and each time you run your code, it counts into the quota. To minimize this effect, use the debugger more often to check for possible errors you may have missed.
Placeholder: Placeholders are a big deal in app script. The wrong placeholder can cause your script not to run as it should or even throw an error. If you are to use placeholders in your script, check them over and over again.
Permissions: I will advise anyone using app script not to run a script they didn’t create on their Google account. This is because App Script can write on the tool it was given access to. Executing a code you didn’t create means that there might be snippets that can cause harm to your files in it.
If you must use an app script you didn’t create, ensure you trust the source.
Minimize API calls: Use less API calls so as not to cause too much load on the system. Excessive use of API calls can lead to malfunctioning or non-executing scripts.
Observe general programming procedures: Clarity with commenting, clean codes, proper structures, error handling. Etc.
Always keep document’s tabs open when referencing them: This ensures that App Script can access the file you have specified.
Conclusion
Apps Script opens a world of automation for Google Workspace tools. By leveraging the examples in this guide, you can enhance your productivity, cut down recurring tasks and streamline your operation especially if you work with Google Workspace tools a lot.
If you’d want to learn more on how to use App Script for more advanced stuff, you can visit the Apps Script Documentation.