Class Document

Document

A document, containing one or moreTab objects, each of which contains rich text andelements such as tables and lists.

Documents may be opened or created usingDocumentApp.

// Open a document by ID.letdoc=DocumentApp.openById('<my-id>');// Create and open a document.doc=DocumentApp.create('Document Title');

Methods on theDocument class that directly access and modify text contents operate oneither the active tab (in scriptsbound to aparticular document) or the first tab (if an active one isn't available). Scripts relying onthese methods (for example,getBody()) can be migrated to support tabs usinggetTabs() and thenTab.asDocumentTab().

Methods

MethodReturn typeBrief description
addBookmark(position)BookmarkAdds aBookmark at the givenPosition to the first tab or, for scripts that arebound to a document, the active tab.
addEditor(emailAddress)DocumentAdds the given user to the list of editors for theDocument.
addEditor(user)DocumentAdds the given user to the list of editors for theDocument.
addEditors(emailAddresses)DocumentAdds the given array of users to the list of editors for theDocument.
addFooter()FooterSectionAdds a footer section, if none exists, to the first tab or, for scripts that arebound to a document, the active tab.
addHeader()HeaderSectionAdds a header section, if none exists, to the first tab or, for scripts that arebound to a document, the active tab.
addNamedRange(name, range)NamedRangeAdds aNamedRange, which is aRange that has a name and ID to use forlater retrieval, in the first tab or, for scripts that arebound to a document, the active tab.
addViewer(emailAddress)DocumentAdds the given user to the list of viewers for theDocument.
addViewer(user)DocumentAdds the given user to the list of viewers for theDocument.
addViewers(emailAddresses)DocumentAdds the given array of users to the list of viewers for theDocument.
getActiveTab()TabGets the user's currently activeTab in the document.
getAs(contentType)BlobRetrieves the currentDocument contents as a blob of the specified type.
getBlob()BlobRetrieves the currentDocument contents as a blob.
getBody()BodyRetrieves the first tab'sBody or, for scripts that arebound to a document, the active tab'sDocumentBodySection.
getBookmark(id)BookmarkGets theBookmark with the given ID in the first tab or, for scripts that arebound to a document, the active tab.
getBookmarks()Bookmark[]Gets allBookmark objects in the first tab or, for scripts that arebound to a document, the active tab.
getCursor()PositionGets the user's cursor in the active tab.
getEditors()User[]Gets the list of editors for thisDocument.
getFooter()FooterSectionRetrieves the first tab's footer section or, for scripts that arebound to a document, the active tab's footersection.
getFootnotes()Footnote[]Retrieves all theFootnote elements in the first tab's body or, for scripts that arebound to a document, the active tab's body.
getHeader()HeaderSectionRetrieves the first tab's header section or, for scripts that arebound to a document, the active tab's headersection.
getId()StringRetrieves the document's unique identifier.
getLanguage()StringGets the document's language code.
getName()StringRetrieves the title of the document.
getNamedRangeById(id)NamedRangeGets theNamedRange with the given ID in the first tab or, for scripts that arebound to a document, the active tab.
getNamedRanges()NamedRange[]Gets allNamedRange objects in the first tab or, for scripts that arebound to a document, the active tab.
getNamedRanges(name)NamedRange[]Gets allNamedRange objects with the given name in the first tab or, for scripts thatarebound to a document, the active tab.
getSelection()RangeGets the user's selection in the active tab.
getSupportedLanguageCodes()String[]Gets all language codes that are supported in Google Docs files.
getTab(tabId)TabGets theTab with the specified ID.
getTabs()Tab[]Gets all unnestedTabs that are part of the document.
getUrl()StringRetrieves the URL to access the current document.
getViewers()User[]Gets the list of viewers and commenters for thisDocument.
newPosition(element, offset)PositionCreates a newPosition, which is a reference to a location in the tab, relative to aspecific element in the first tab or, for scripts that arebound to a document, the active tab.
newRange()RangeBuilderCreates a builder used to constructRange objects from tab elements in thefirst tab or, for scripts that arebound to adocument, the active tab.
removeEditor(emailAddress)DocumentRemoves the given user from the list of editors for theDocument.
removeEditor(user)DocumentRemoves the given user from the list of editors for theDocument.
removeViewer(emailAddress)DocumentRemoves the given user from the list of viewers and commenters for theDocument.
removeViewer(user)DocumentRemoves the given user from the list of viewers and commenters for theDocument.
saveAndClose()voidSaves the currentDocument.
setActiveTab(tabId)voidSets the user's selectedTab in the current document to the tab with the specified ID.
setCursor(position)DocumentSets the user's cursor, given aPosition.
setLanguage(languageCode)DocumentSets the document's language code.
setName(name)DocumentSets the document title.
setSelection(range)DocumentSets the user's selection in the active tab, given aRange.

Detailed documentation

addBookmark(position)

Adds aBookmark at the givenPosition to the first tab or, for scripts that arebound to a document, the active tab. To add abookmark to any tab, use theDocumentTab.addBookmark(position) method.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.// TODO(developer): Replace the ID with your own.constdoc=DocumentApp.openById('123abc');// Gets the active or first tab's body and adds a paragraph.constparagraph=doc.getBody().appendParagraph('My new paragraph.');// Creates a position at the first character of the paragraph text.constposition=doc.newPosition(paragraph.getChild(0),0);// Adds a bookmark at the first character of the paragraph text.constbookmark=doc.addBookmark(position);// Logs the bookmark ID to the console.console.log(bookmark.getId());

Parameters

NameTypeDescription
positionPositionThe position of the new bookmark.

Return

Bookmark — The new bookmark.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

addEditor(emailAddress)

Adds the given user to the list of editors for theDocument. If the user was alreadyon the list of viewers, this method promotes the user out of the list of viewers.

Parameters

NameTypeDescription
emailAddressStringThe email address of the user to add.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

addEditor(user)

Adds the given user to the list of editors for theDocument. If the user was alreadyon the list of viewers, this method promotes the user out of the list of viewers.

Parameters

NameTypeDescription
userUserA representation of the user to add.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

addEditors(emailAddresses)

Adds the given array of users to the list of editors for theDocument. If any of theusers were already on the list of viewers, this method promotes them out of the list ofviewers.

Parameters

NameTypeDescription
emailAddressesString[]An array of email addresses of the users to add.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

addFooter()

Adds a footer section, if none exists, to the first tab or, for scripts that arebound to a document, the active tab. To add a footersection to any tab, use theDocumentTab.addFooter() method.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.// TODO(developer): Replace the ID with your own.constdoc=DocumentApp.openById('123abc');// Adds a footer to the document's active or first tab.constfooter=doc.addFooter();// Sets the footer text to 'This is a footer.'footer.setText('This is a footer');

Return

FooterSection — The tab footer.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

addHeader()

Adds a header section, if none exists, to the first tab or, for scripts that arebound to a document, the active tab. To add a headersection to any tab, use theDocumentTab.addHeader() method.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.// TODO(developer): Replace the ID with your own.constdoc=DocumentApp.openById('123abc');// Adds a header to the document's active or first tab.constheader=doc.addHeader();// Sets the header text to 'This is a header.'header.setText('This is a header');

Return

HeaderSection — The tab header.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

addNamedRange(name, range)

Adds aNamedRange, which is aRange that has a name and ID to use forlater retrieval, in the first tab or, for scripts that arebound to a document, the active tab. To add aNamedRange in any tab, use theDocumentTab.addNamedRange(name, range) method. Names aren'tnecessarily unique; several different ranges in the same document can share the same name, muchlike a class in HTML. By contrast, IDs are unique within the document, like an ID in HTML.After you add aNamedRange to a document, you can't modify it, you can only remove it.

Any script that accesses the document can access aNamedRange. To avoid unintendedconflicts between scripts, consider prefixing range names with a unique string.

// Creates a named range that includes every table in the active tab.constdoc=DocumentApp.getActiveDocument();constrangeBuilder=doc.newRange();consttables=doc.getBody().getTables();for(leti=0;i <tables.length;i++){rangeBuilder.addElement(tables[i]);}// Adds the named range to the document's active tab.doc.addNamedRange('Document tables',rangeBuilder.build());

Parameters

NameTypeDescription
nameStringThe name for the range, which doesn't need to be unique; range names must be between 1-256 characters.
rangeRangeThe range of elements to associate with the name; the range can bethe active selection, asearch result, or manually constructed withnewRange().

Return

NamedRange — TheNamedRange.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

addViewer(emailAddress)

Adds the given user to the list of viewers for theDocument. If the user was alreadyon the list of editors, this method has no effect.

Parameters

NameTypeDescription
emailAddressStringThe email address of the user to add.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

addViewer(user)

Adds the given user to the list of viewers for theDocument. If the user was alreadyon the list of editors, this method has no effect.

Parameters

NameTypeDescription
userUserA representation of the user to add.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

addViewers(emailAddresses)

Adds the given array of users to the list of viewers for theDocument. If any of theusers were already on the list of editors, this method has no effect for them.

Parameters

NameTypeDescription
emailAddressesString[]An array of email addresses of the users to add.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getActiveTab()

Gets the user's currently activeTab in the document. A script can only access theactive tab of the user who is running the script, and only if the script isbound to the document.

// Display a dialog box that shows the title of the tab that the// user is currently viewing.consttab=DocumentApp.getActiveDocument().getActiveTab();DocumentApp.getUi().alert(`ID of selected tab:${tab.getTitle()}`);

Return

Tab — The user's currently activeTab, ornull if the script is not bound to the document.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getAs(contentType)

Retrieves the currentDocument contents as a blob of the specified type.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.// TODO(developer): Replace the ID with your own.constdoc=DocumentApp.openById('123abc');// Gets the document as a PDF.constpdf=doc.getAs('application/pdf');// Logs the name of the PDF to the console.console.log(pdf.getName());

Parameters

NameTypeDescription
contentTypeStringThe MIME type to convert to;'application/pdf' and'text/markdown' are supported.

Return

Blob — The current document as a blob.


getBlob()

Retrieves the currentDocument contents as a blob.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.// TODO(developer): Replace the ID with your own.constdoc=DocumentApp.openById('123abc');// Retrieves the current document's contents as a blob and logs it to the// console.console.log(doc.getBlob().getContentType());

Return

Blob — The current document as a blob.


getBody()

Retrieves the first tab'sBody or, for scripts that arebound to a document, the active tab'sDocumentBodySection. To get theDocumentBodySection of any tab, use theDocumentTab.getBody() method.

Tabs may contain different types of sections (for example,HeaderSection,FooterSection). The active section for a tab is theBody.

Element methods inDocument delegate to the activeBody.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.// TODO(developer): Replace the ID with your own.constdoc=DocumentApp.openById('123abc');// Gets the active or first tab's body.constbody=doc.getBody();// Gets the body text and logs it to the console.console.log(body.getText());

Return

Body — The tab body section.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getBookmark(id)

Gets theBookmark with the given ID in the first tab or, for scripts that arebound to a document, the active tab. To get abookmark in any tab, use theDocumentTab.getBookmark(id) method. This method returnsnull if no suchBookmark exists within the tab.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.// TODO(developer): Replace the ID with your own.constdoc=DocumentApp.openById('123abc');// Gets the bookmark by its ID in the document's active or first tab.constbookmark=doc.getBookmark('id.xyz654321');// If the bookmark exists, logs the character offset of its position to the// console. otherwise, logs 'No bookmark exists with the given ID.' to the// console.if(bookmark){console.log(bookmark.getPosition().getOffset());}else{console.log('No bookmark exists with the given ID.');}

Parameters

NameTypeDescription
idStringThe ID for theBookmark.

Return

Bookmark — TheBookmark with the given ID, ornull if no suchBookmark exists within the tab.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getBookmarks()

Gets allBookmark objects in the first tab or, for scripts that arebound to a document, the active tab. To get allbookmarks in any tab, use theDocumentTab.getBookmarks() method.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.constdoc=DocumentApp.openById('123abc');// Gets all of the bookmarks in the document's active or first tab.constbookmarks=doc.getBookmarks();// Logs the number of bookmarks in the tab to the console.console.log(bookmarks.length);

Return

Bookmark[] — An array of theBookmark objects in the tab.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getCursor()

Gets the user's cursor in the active tab. A script can only access the cursor of the user whois running the script, and only if the script isbound to the document.

// Insert some text at the cursor position and make it bold.constcursor=DocumentApp.getActiveDocument().getCursor();if(cursor){// Attempt to insert text at the cursor position. If the insertion returns// null, the cursor's containing element doesn't allow insertions, so show the// user an error message.constelement=cursor.insertText('ಠ‿ಠ');if(element){element.setBold(true);}else{DocumentApp.getUi().alert('Cannot insert text here.');}}else{DocumentApp.getUi().alert('Cannot find a cursor.');}

Return

Position — A representation of the user's cursor, ornull if the user does not have a cursor placed in the tab or if the script is not bound to the document.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getEditors()

Gets the list of editors for thisDocument.

Return

User[] — An array of users with edit permission.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getFooter()

Retrieves the first tab's footer section or, for scripts that arebound to a document, the active tab's footersection. To get the footer section of any tab, use theDocumentTab.getFooter() method.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.// TODO(developer): Replace the ID with your own.constdoc=DocumentApp.openById('123abc');// Gets the text of the active or first tab's footer and logs it to the console.console.log(doc.getFooter().getText());

Return

FooterSection — The tab's footer.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getFootnotes()

Retrieves all theFootnote elements in the first tab's body or, for scripts that arebound to a document, the active tab's body. To getall the footnotes in any tab, use theDocumentTab.getFootnotes() method.

Calls togetFootnotes cause an iteration over the tab's elements. For large tabs,avoid unnecessary calls to this method.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.// TODO(developer): Replace the ID with your own.constdoc=DocumentApp.openById('123abc');// Gets the first footnote in the active or first tab's body.constfootnote=doc.getFootnotes()[0];// Logs footnote contents to the console.console.log(footnote.getFootnoteContents().getText());

Return

Footnote[] — The tab's footnotes.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getHeader()

Retrieves the first tab's header section or, for scripts that arebound to a document, the active tab's headersection. To get the header section of any tab, use theDocumentTab.getHeader() method.

// Opens the Docs file by its ID. If you created your script from within// a Google Docs file, you can use DocumentApp.getActiveDocument() instead.// TODO(developer): Replace the ID with your own.constdoc=DocumentApp.openById('123abc');// Gets the text of the active or first tab's header and logs it to the console.console.log(doc.getHeader().getText());

Return

HeaderSection — The tab's header.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getId()

Retrieves the document's unique identifier. The document ID is used withDocumentApp.openById() to open a specific document instance.

Return

String — The document's ID.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getLanguage()

Gets the document's language code. This is the language shown in the document editor'sFile> Language, which may not be the actual language that the document contains.

Return

String — The document language, ornull if not defined.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getName()

Retrieves the title of the document.

Return

String — The document title.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getNamedRangeById(id)

Gets theNamedRange with the given ID in the first tab or, for scripts that arebound to a document, the active tab. To get theNamedRange with the given ID in any tab, use theDocumentTab.getNamedRangeById(id)method. This method returnsnull if no suchNamedRange exists in the tab. Namesare not necessarily unique, even across tabs; several different ranges in the same tab mayshare the same name, much like a class in HTML. By contrast, IDs are unique within the tab,like an ID in HTML.

Parameters

NameTypeDescription
idStringThe range's ID, which is unique within the tab.

Return

NamedRange — TheNamedRange with the given ID, ornull if no such range exists in the tab.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getNamedRanges()

Gets allNamedRange objects in the first tab or, for scripts that arebound to a document, the active tab. To get allNamedRange objects in any tab, use theDocumentTab.getNamedRanges() method.

ANamedRange can be accessed by any script that accesses the tab. To avoidunintended conflicts between scripts, consider prefixing range names with a unique string.

Return

NamedRange[] — An array of theNamedRange objects in the tab, possibly including multiple ranges with the same name.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getNamedRanges(name)

Gets allNamedRange objects with the given name in the first tab or, for scripts thatarebound to a document, the active tab. To getallNamedRange objects in any tab, use theDocumentTab.getNamedRanges(name) method. Names are not necessarily unique, even across tabs; several different ranges inthe same tab may share the same name, much like a class in HTML. By contrast, IDs are uniquewithin the tab, like an ID in HTML.

ANamedRange can be accessed by any script that accesses the document. To avoidunintended conflicts between scripts, consider prefixing range names with a unique string.

Parameters

NameTypeDescription
nameStringThe range's name, which is not necessarily unique.

Return

NamedRange[] — An array of theNamedRange objects in the tab with the given name.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getSelection()

Gets the user's selection in the active tab. A script can only access the selection of the userwho is running the script, and only if the script isbound to the document.

// Display a dialog box that tells the user how many elements are included in// the selection.constselection=DocumentApp.getActiveDocument().getSelection();if(selection){constelements=selection.getRangeElements();DocumentApp.getUi().alert(`Number of selected elements:${elements.length}`);}else{DocumentApp.getUi().alert('Nothing is selected.');}

Return

Range — A representation of the user's selection, ornull if the user does not have anything selected in the tab, if only the end of a paragraph is selected, if only the end of a paragraph and a new line are selected, or if the script is not bound to the document.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getSupportedLanguageCodes()

Gets all language codes that are supported in Google Docs files.

Return

String[] — An array of language codes.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getTab(tabId)

Gets theTab with the specified ID. This method returnsnull if no suchTab exists. Can access tabs at any nesting level.

Parameters

NameTypeDescription
tabIdStringThe ID of the tab to get.

Return

Tab — TheTab with the specified ID, ornull if no suchTab exists.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getTabs()

Gets all unnestedTabs that are part of the document.

Tabs can contain child tabs, a tab nested within another tab. Child tabs are accessibleusingTab.getChildTabs().

Return

Tab[] — The list of allTabs that are part of the document.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getUrl()

Retrieves the URL to access the current document.

constdoc=DocumentApp.getActiveDocument();// Send out the link to open the document.MailApp.sendEmail('<email-address>',doc.getName(),doc.getUrl());

Return

String — The URL to access the current document.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getViewers()

Gets the list of viewers and commenters for thisDocument.

Return

User[] — An array of users with view or comment permission.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

newPosition(element, offset)

Creates a newPosition, which is a reference to a location in the tab, relative to aspecific element in the first tab or, for scripts that arebound to a document, the active tab. To create aPosition relative to a location in any tab, use theDocumentTab.newPosition(element, offset)method. The user's cursor is represented as aPosition, among other uses.

// Append a paragraph to the active tab, then place the user's cursor after the// first word of the new paragraph.constdoc=DocumentApp.getActiveDocument();constparagraph=doc.getBody().appendParagraph('My new paragraph.');constposition=doc.newPosition(paragraph.getChild(0),2);doc.setCursor(position);

Parameters

NameTypeDescription
elementElementThe element that should contain the newPosition; this must be either aText element or a container element likeParagraph.
offsetIntegerForText elements, the number of characters before thePosition; for other elements, the number of child elements before thePosition within the same container element.

Return

Position — The newPosition.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

newRange()

Creates a builder used to constructRange objects from tab elements in thefirst tab or, for scripts that arebound to adocument, the active tab. To create a builder used to constructDocumentRange objectsfrom tab elements in any tab, use theDocumentTab.newRange() method.

// Change the user's selection to a range that includes every table in the// active tab.constdoc=DocumentApp.getActiveDocument();constrangeBuilder=doc.newRange();consttables=doc.getBody().getTables();for(leti=0;i <tables.length;i++){rangeBuilder.addElement(tables[i]);}doc.setSelection(rangeBuilder.build());

Return

RangeBuilder — The new builder.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

removeEditor(emailAddress)

Removes the given user from the list of editors for theDocument. This method doesn'tblock users from accessing theDocument if they belong to a class of users who havegeneral access—for example, if theDocument is shared with the user's entiredomain, or if theDocument is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of viewers.

Parameters

NameTypeDescription
emailAddressStringThe email address of the user to remove.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

removeEditor(user)

Removes the given user from the list of editors for theDocument. This method doesn'tblock users from accessing theDocument if they belong to a class of users who havegeneral access—for example, if theDocument is shared with the user's entiredomain, or if theDocument is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of viewers.

Parameters

NameTypeDescription
userUserA representation of the user to remove.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

removeViewer(emailAddress)

Removes the given user from the list of viewers and commenters for theDocument. Thismethod has no effect if the user is an editor, not a viewer or commenter. This method alsodoesn't block users from accessing theDocument if they belong to a class of users whohave general access—for example, if theDocument is shared with the user'sentire domain, or if theDocument is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of editors.

Parameters

NameTypeDescription
emailAddressStringThe email address of the user to remove.

Return

Document — ThisDocument for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

removeViewer(user)

Removes the given user from the list of viewers and commenters for theDocument. Thismethod has no effect if the user is an editor, not a viewer. This method also doesn't blockusers from accessing theDocument if they belong to a class of users who have generalaccess—for example, if theDocument is shared with the user's entire domain, orif theDocument is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of editors.

Parameters

NameTypeDescription
userUserA representation of the user to remove.

Return

Document — ThisDocument for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

saveAndClose()

Saves the currentDocument. Causes pending updates to be flushed and applied.

ThesaveAndClose() method is automatically invoked at the end of script executionfor each open editableDocument.

A closedDocument can't be edited. UseDocumentApp.openById() to reopen agiven document for editing.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setActiveTab(tabId)

Sets the user's selectedTab in the current document to the tab with the specified ID.

constdoc=DocumentApp.getActiveDocument();// Sets the user's selected tab by its ID.// TODO(developer): Replace the ID with your own.consttab=doc.setActiveTab('123abc');

Parameters

NameTypeDescription
tabIdStringThe ID of the tab to set as active.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setCursor(position)

Sets the user's cursor, given aPosition. A script can only access the cursor of theuser who is running the script, and only if the script isbound to the document.

Providing aPosition from an inactiveTab switches the user's active tab.

constdoc=DocumentApp.getActiveDocument();constdocumentTab=doc.getActiveTab().asDocumentTab();// Append a paragraph, then place the user's cursor after the first word of the// new paragraph.constparagraph=documentTab.getBody().appendParagraph('My new paragraph.');constposition=documentTab.newPosition(paragraph.getChild(0),2);doc.setCursor(position);

Parameters

NameTypeDescription
positionPositionThe new cursor location.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setLanguage(languageCode)

Sets the document's language code. This is the language shown in the document editor'sFile> Language, which may not be the actual language that the document contains. UsegetSupportedLanguageCodes() to get all the valid language codes.

Parameters

NameTypeDescription
languageCodeStringThe language code.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setName(name)

Sets the document title.

Parameters

NameTypeDescription
nameStringThe new document title.

Return

Document — The current document.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setSelection(range)

Sets the user's selection in the active tab, given aRange. A script can onlyaccess the selection of the user who is running the script, and only if the script isbound to the document.

constdoc=DocumentApp.getActiveDocument();constdocumentTab=doc.getActiveTab().asDocumentTab();// Change the user's selection to a range that includes every table in the// document.constrangeBuilder=documentTab.newRange();consttables=documentTab.getBody().getTables();for(leti=0;i <tables.length;i++){rangeBuilder.addElement(tables[i]);}doc.setSelection(rangeBuilder.build());

Parameters

NameTypeDescription
rangeRangeThe new range of elements to select.

Return

Document — ThisDocument, for chaining.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

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 2024-12-03 UTC.