I offer a different, shorter answer to your first question regarding enumerating all the links in the body of a document. This instructional code returns a flat array of links in the current document body, where each link is represented by an object with records pointing to a text element ( text ), a paragraph element or the list item in which it was contained ( paragraph ), an index offset in the text where the link appears ( startOffset ) and the URL itself ( url ). I hope you find it easy to pick it up for your own needs.
It uses the getTextAttributeIndices() method and does not iterate over each character of the text, and therefore it is expected to work much faster than the previously written answers.
EDIT : Since publishing this answer, I modified the function several times. Now it also (1) includes the endOffsetInclusive property for each link (note that it can be null for links that extend to the end of the text element - in this case, you can use link.text.length-1 instead); (2) finds links in all sections of the document, and not just in the body, and (3) includes section and isFirstPageSection properties in isFirstPageSection to indicate where the link is; (4) accepts the argument mergeAdjacent , which, with mergeAdjacent true, will return only one link entry for a continuous segment of text associated with the same URL (which will be considered separate if, for example, part of the text is decorated differently) than the other part) .
To include links in all sections, a new iterateSections() utility function was introduced.
function getAllLinks(mergeAdjacent) { var links = []; var doc = DocumentApp.getActiveDocument(); iterateSections(doc, function(section, sectionIndex, isFirstPageSection) { if (!("getParagraphs" in section)) {
Yuval
source share