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.