0

Insert Text

by
Published today

Insert text into a Google Doc at an index, or append it at the end.

Script gdocs Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 hours 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.
6
 */
7
export async function main(
8
  auth: RT.Gdocs,
9
  document_id: string,
10
  text: string,
11
  index: number | undefined
12
) {
13
  const response = await fetch(
14
    `https://docs.googleapis.com/v1/documents/${document_id}:batchUpdate`,
15
    {
16
      method: "POST",
17
      headers: {
18
        Authorization: `Bearer ${auth.token}`,
19
        "Content-Type": "application/json",
20
        Accept: "application/json",
21
      },
22
      body: JSON.stringify({
23
        requests: [
24
          {
25
            insertText:
26
              index === undefined
27
                ? { text, endOfSegmentLocation: {} }
28
                : { text, location: { index } },
29
          },
30
        ],
31
      }),
32
    }
33
  )
34
  if (!response.ok) {
35
    throw new Error(`${response.status} ${await response.text()}`)
36
  }
37

38
  return await response.json()
39
}
40