0

List Tabs

by
Published today

List a Google Doc's tabs and child tabs with their ids.

Script gdocs Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 hours ago
1
//native
2

3
/**
4
 * List Tabs
5
 * List a Google Doc's tabs, child tabs included, in document order with their `tab_id`, title, index, nesting level and parent. Tab ids are what the other Docs scripts take as `tab_id`; every document has at least one tab.
6
 */
7
export async function main(auth: RT.Gdocs, document_id: string) {
8
  const url = new URL(`https://docs.googleapis.com/v1/documents/${document_id}`)
9
  url.searchParams.append("includeTabsContent", "true")
10
  // Metadata only: nesting is capped at 3 levels, and childTabs without a mask would pull every tab's body.
11
  url.searchParams.append(
12
    "fields",
13
    "tabs(tabProperties,childTabs(tabProperties,childTabs(tabProperties)))"
14
  )
15
  const response = await fetch(url, {
16
    headers: {
17
      Authorization: `Bearer ${auth.token}`,
18
      Accept: "application/json",
19
    },
20
  })
21
  if (!response.ok) {
22
    throw new Error(`${response.status} ${await response.text()}`)
23
  }
24

25
  const { tabs } = (await response.json()) as { tabs?: Tab[] }
26
  const out: any[] = []
27
  const walk = (ts: Tab[]) =>
28
    ts.forEach((t) => {
29
      const p = t.tabProperties
30
      out.push({
31
        tab_id: p.tabId,
32
        title: p.title,
33
        index: p.index ?? 0,
34
        nesting_level: p.nestingLevel ?? 0,
35
        parent_tab_id: p.parentTabId,
36
      })
37
      walk(t.childTabs ?? [])
38
    })
39
  walk(tabs ?? [])
40
  return out
41
}
42

43
type Tab = {
44
  tabProperties: {
45
    tabId: string
46
    title: string
47
    index?: number
48
    nestingLevel?: number
49
    parentTabId?: string
50
  }
51
  childTabs?: Tab[]
52
}
53