Extending Google Docs

  • Google Apps Script can create and modify Google Docs and customize their user interface.

  • Apps Script can interact with Google Docs by either creating or modifying a document with appropriate permissions or by being bound to a document for special UI abilities.

  • ThereplaceText() method in Apps Script is a simple way to replace text in a Google Doc and supports regular expressions.

  • Custom menus, dialog boxes, and sidebars can be added to Google Docs using Apps Script, but the script must be bound to the document.

  • Scripts for Google Docs can be published as add-ons to share them with other users.

Google Apps Script allows you to programmatically create and modify Google Docs,as well as customize the user interface with new menus, dialog boxes, andsidebars.

The basics

Apps Script can interact with Google Docs in two broad ways: any script cancreate or modify a document if the script's user has appropriate permissions forthe document, and a script can also bebound to a document, which givesthe script special abilities to alter the user interface or respond when thedocument is opened. To create a container-bound script from within Google Docs,clickExtensions>Apps Script.

In either case, it's simple to interact with a Google Docs document throughApps Script'sDocument Service, as the following exampledemonstrates.

functioncreateDoc(){vardoc=DocumentApp.create('Sample Document');vardocumentTab=doc.getTab('t.0').asDocumentTab();varbody=documentTab.getBody();varrowsData=[['Plants','Animals'],['Ficus','Goat'],['Basil','Cat'],['Moss','Frog']];body.insertParagraph(0,doc.getName()).setHeading(DocumentApp.ParagraphHeading.HEADING1);table=body.appendTable(rowsData);table.getRow(0).editAsText().setBold(true);}

The script above creates a new document in the user's Google Drive, thenretrieves the tab with IDt.0 (the default first tab), inserts a paragraphthat contains the same text as the document's name, styles that paragraph as aheading, and appends a table based on the values in a two-dimensional array. Thescript could just as easily make these changes to an existing document byreplacing the call toDocumentApp.create()withDocumentApp.openById()oropenByUrl().For scripts created inside a document (container-bound), useDocumentApp.getActiveDocument()andDocument.getActiveTab().

Structure of a document

From Apps Script's perspective, a Google Docs document is structuredmuch like an HTML document—that is, a document is composed of one or moreTab objects, each of which containelements (like aParagraph orTable) that often contain otherelements. Most scripts that modify a Google Docs document begin with a call togetTab() andasDocumentTab()followed bygetBody(),because theBody is a core elementthat contains all other elements in a tab except for theHeaderSection,FooterSection, and anyFootnotes.

However, there are rules about which types of elements can contain other types.Furthermore, the Document Service in Apps Script can only insertcertain types of elements into other elements. The tree below shows whichelements can be contained by a certain type of element.

Elements shown in bold can be inserted; non-bold elements can only bemanipulated in place.

Replacing text

Apps Script is often used to replace text in Google Docs. Let's say you have aspreadsheet full of client information and you want to generate a personalizedGoogle Docs for each client. (This type of operation is often called a mailmerge.)

There are many ways to replace text, but the simplest is thereplaceText() method shown in the example below.replaceText supports mostof JavaScript'sregular expression features. The first function belowadds several lines of placeholder text to a Google Docs; in the real world, youwould be more likely to type the placeholders into the document yourself. Thesecond function replaces the placeholders with properties defined in theclient object.

Note that both of these functions use thegetActiveDocument()andgetActiveTab()methods, which only apply to scripts created inside a Google Docs document;in a stand-alone script, useDocumentApp.create(),openById(),oropenByUrl(),combined withDocument.getTab(),instead.

Add some placeholders

functioncreatePlaceholders(){varbody=DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();body.appendParagraph('{name}');body.appendParagraph('{address}');body.appendParagraph('{city} {state} {zip}');}

Replace the placeholders

functionsearchAndReplace(){varbody=DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();varclient={name:'Joe Script-Guru',address:'100 Script Rd',city:'Scriptville',state:'GA',zip:94043};body.replaceText('{name}',client.name);body.replaceText('{address}',client.address);body.replaceText('{city}',client.city);body.replaceText('{state}',client.state);body.replaceText('{zip}',client.zip);}

Custom menus and user interfaces

You can customize Google Docs by adding menus, dialog boxes, andsidebars. Keep in mind, however, that a script can only interact with the UI forthe current instance of an open document, and only if the script isbound to the document.

See how to addcustom menus anddialogs to your Google Docs.To learn more about creating custom interfaces for a dialog or sidebar, see theguide to HTML Service.If you're planning to publish your custom interface as part of anadd-on, follow thestyle guide for consistency with thestyle and layout of the Google Docs editor.

Add-ons for Google Docs

Add-ons run inside Google Docs and can be installedfrom the Google Docs add-on store. If you've developed a script for Google Docsand want to share it with the world, Apps Script lets youpublish your script as anadd-on so other users can install it from the add-on store.

To see how you can create an add-on for Google Docs, seequickstart for building Docs add-ons.

Triggers

Scripts that arebound to a GoogleDoc can use asimple trigger to respondto the document'sonOpenevent, whichoccurs whenever a user who has edit access to the document opens it in Google Docs.

To set up the trigger, just write a function calledonOpen(). For an exampleof this trigger, seeCustom menus in Google Workspace.Although the simple trigger is useful for adding menus, it cannot use any AppsScript services that require authorization.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-11 UTC.