0

Insert Text

by
Published 20 days ago

Insert text at an index or the end of a Google Doc, optionally in a given tab.

Script gdocs Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 8 days ago
1
//native
2

3
/**
4
 * Insert Text
5
 * Insert text into a Google Doc at a character index (1 is the start of the body). Leave `index` empty to append at the end of the document. Set `tab_id` (from List Tabs) to write to a tab other than the first.
6
 */
7
export async function main(
8
  auth: RT.Gdocs,
9
  document_id: string,
10
  text: string,
11
  index: number | undefined,
12
  tab_id: string | undefined
13
) {
14
  const response = await fetch(
15
    `https://docs.googleapis.com/v1/documents/${document_id}:batchUpdate`,
16
    {
17
      method: "POST",
18
      headers: {
19
        Authorization: `Bearer ${auth.token}`,
20
        "Content-Type": "application/json",
21
        Accept: "application/json",
22
      },
23
      body: JSON.stringify({
24
        requests: [
25
          {
26
            insertText:
27
              index == null
28
                ? { text, endOfSegmentLocation: { tabId: tab_id || undefined } }
29
                : { text, location: { index, tabId: tab_id || undefined } },
30
          },
31
        ],
32
      }),
33
    }
34
  )
35
  if (!response.ok) {
36
    throw new Error(`${response.status} ${await response.text()}`)
37
  }
38

39
  return await response.json()
40
}
41