Why do you need to do this with a Script, when InDesign already has a Table of Contents feature under the Layout menu? This feature literally finds all text using the Styles selected along with their page numbers and applies the ToC Paragraph Styles you wish to use.
If all you want is the text, use the Table of Contents feature and export the text in the ToC as a TXT file. Way less time than writing a Script.
And if you check the Bookmarks option, the ToC is automatically interactive in an exported PDF.