While basic Apps Script functions can be run manually, true automation and streamlined workflows come from adding custom user interfaces and leveraging automated triggers. This section will explore how to create custom menus in Google Docs, set up triggers to run scripts automatically, and even build simple user interfaces for more complex interactions.
Adding custom menus to your Google Docs allows users to access your scripts directly from the familiar interface. This makes your automation more accessible and intuitive. We achieve this by using the onOpen() simple trigger.
function onOpen() {
var ui = DocumentApp.getUi();
ui.createMenu('Custom Tools')
.addItem('Format Document', 'formatDocument')
.addSeparator()
.addSubMenu(ui.createMenu('Advanced Options')
.addItem('Add Header', 'addHeader'))
.addToUi();
}
function formatDocument() {
// Your code to format the document goes here
DocumentApp.getActiveDocument().getBody().setAttributes({fontSize: 12, fontWeight: 'normal'});
DocumentApp.getUi().alert('Document formatted!');
}
function addHeader() {
// Your code to add a header goes here
DocumentApp.getActiveDocument().addHeader().insertParagraph(0, 'My Custom Header');
DocumentApp.getUi().alert('Header added!');
}When you open a Google Doc with the script above, a new menu item called 'Custom Tools' will appear in the menu bar. Clicking on it will reveal 'Format Document' and an 'Advanced Options' submenu containing 'Add Header'. The onOpen() function runs automatically when the document is opened, creating these menu items. The other functions, formatDocument() and addHeader(), are the actual scripts that get executed when the corresponding menu items are clicked.
Triggers are the backbone of automation. They allow your Apps Script to run automatically based on specific events, such as time-driven intervals or user actions. There are two main types of triggers: simple triggers and installable triggers.
Simple triggers are pre-defined functions that Apps Script automatically runs when certain events occur. Examples include onOpen(), onEdit(), and onInstall(). They have some limitations, such as not being able to access services that require authorization, but they are excellent for basic tasks.
function onEdit(e) {
var range = e.range;
var sheet = range.getSheet();
var col = range.getColumn();
var row = range.getRow();
if (sheet.getName() === 'Sheet1' && col === 2 && row > 1) {
var timestamp = new Date();
sheet.getRange(row, 3).setValue(timestamp);
}
}This onEdit(e) function will automatically add a timestamp to column C whenever a value is edited in column B of 'Sheet1', skipping the header row. The e parameter provides information about the edit event.
Installable triggers offer more power and flexibility. They can be set up for a wider range of events and can access all Google Apps services, even those requiring authorization. You can create installable triggers from within the Apps Script editor.
graph TD
A[Script Editor] --> B{Triggers Menu}
B --> C{Add Trigger}
C --> D[Select Function]
D --> E[Select Event Source (e.g., Time-driven, Spreadsheet)]
E --> F[Configure Event Settings (e.g., Time interval, Sheet name)]
F --> G[Save Trigger]
Common installable trigger types include:
- Time-driven: Run a script at a specified interval (e.g., daily, hourly).
- Spreadsheet-driven: Triggered by events in a Google Sheet (e.g.,
onOpen,onEdit,onFormSubmit). - Calendar-driven: Triggered by events in Google Calendar.
- Document-driven: Triggered by events in Google Docs.
- Form-driven: Triggered when a Google Form is submitted.
For more interactive automation, you can build custom user interfaces using the HTML Service. This allows you to create dialogs, sidebars, or even custom web apps that interact with your Google Workspace data. You'll typically write HTML, CSS, and JavaScript for your UI, and use Apps Script to serve this content and handle communication between the UI and your backend script.
// Code.gs
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('Sidebar')
.setTitle('My Custom Sidebar');
DocumentApp.getUi().showSidebar(html);
}
function processData(data) {
// Process data received from the sidebar
Logger.log('Received data: ' + data);
return 'Data processed successfully!';
}// Sidebar.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Enter Data</h1>
<input type="text" id="myInput">
<button onclick="sendData()">Submit</button>
<script>
function sendData() {
var input = document.getElementById('myInput').value;
google.script.run.withSuccessHandler(updateStatus).processData(input);
}
function updateStatus(message) {
alert(message);
}
</script>
</body>
</html>In this example, showSidebar() creates an HTML output from a file named 'Sidebar.html' and displays it as a sidebar in Google Docs. The HTML file contains a simple input field and a button. When the button is clicked, the sendData() JavaScript function in the HTML calls the processData() Apps Script function using google.script.run, passing the input value. The processData() function then logs the data and returns a success message, which is displayed back to the user in an alert box via updateStatus().
By mastering custom menus, triggers, and the HTML Service, you can elevate your Google Apps Script skills from simple automation to sophisticated workflow solutions, significantly boosting your productivity.