メソッドは、asTableOfContents()
エディターのオートコンプリート機能を支援するためにのみ存在します。実行時の影響はなく、別の型へのキャストには使用できません。( ContainerElement のドキュメントを参照してください。)
目次を解析するには、まずSearchResultから要素を取得します。以下は、ドキュメントの目次の項目を調べて、項目情報の配列を生成する例です。
文書例

解析結果
いくつかの見出しと目次を含む単純なドキュメントでは、次のような結果が得られました。
[13-08-20 16:31:56:415 EDT]
[
{text=Heading 1.0, linkUrl=#heading=h.50tkhklducwk, indentFirstLine=18.0, indentStart=18.0},
{text=Heading 1.1, linkUrl=#heading=h.ugj69zpoikat, indentFirstLine=36.0, indentStart=36.0},
{text=Heading 1.2, linkUrl=#heading=h.xb0y0mu59rag, indentFirstLine=36.0, indentStart=36.0},
{text=Heading 2.0, linkUrl=#heading=h.gebx44eft4kq, indentFirstLine=18.0, indentStart=18.0}
]
コード
function test_parseTOC() {
var fileId = '--Doc-ID--';
Logger.log( parseTOC( fileId ) );
}
function parseTOC( docId ) {
var contents = [];
var doc = DocumentApp.openById(docId);
// Define the search parameters.
var searchElement = doc.getBody();
var searchType = DocumentApp.ElementType.TABLE_OF_CONTENTS;
// Search for TOC. Assume there's only one.
var searchResult = searchElement.findElement(searchType);
if (searchResult) {
// TOC was found
var toc = searchResult.getElement().asTableOfContents();
// Parse all entries in TOC. The TOC contains child Paragraph elements,
// and each of those has a child Text element. The attributes of both
// the Paragraph and Text combine to make the TOC item functional.
var numChildren = toc.getNumChildren();
for (var i=0; i < numChildren; i++) {
var itemInfo = {}
var tocItem = toc.getChild(i).asParagraph();
var tocItemAttrs = tocItem.getAttributes();
var tocItemText = tocItem.getChild(0).asText();
// Set itemInfo attributes for this TOC item, first from Paragraph
itemInfo.text = tocItem.getText(); // Displayed text
itemInfo.indentStart = tocItem.getIndentStart(); // TOC Indentation
itemInfo.indentFirstLine = tocItem.getIndentFirstLine();
// ... then from child Text
itemInfo.linkUrl = tocItemText.getLinkUrl(); // URL Link in document
contents.push(itemInfo);
}
}
// Return array of objects containing TOC info
return contents;
}
悪いニュース
悪いニュースは、スクリプトから目次に対してできることが限られていることです。TOC を挿入したり、新しいアイテムを既存のものに追加したりすることはできません。
イシュー トラッカーでイシュー 2502を参照し、更新のためにスターを付けてください。
コードを投稿したり、DocsList と DocumentApp の問題を説明したりできる場合は、それを調べることができます。Google ドキュメントの要素は、DocumentApp を介してのみ操作できます。