Search code examples
google-apps-scriptgoogle-docs-api

Google Apps Script DocumentApp (not SpreadSheet) get hyperlinks embedded in the Document


For a scripting project (using Google Apps Script) I need to get contents of a Google Document and parse through the contents. I can do this by using

  var doc = DocumentApp.openById('xxx')
  var d = doc.getBody().getText()
  Logger.log(d)

But this gets all the contents in form of a text. In the same document I expect to have hyperlinks. I need to get these hyperlinks to perform some action.

I know this can be done in SpreadSheetApp. I also see examples to insert Hyperlink text in a Google Document. But I am unable to find a way to get embedded hyperlink URLs from the Document.

Appreciate any help or suggestions. TIA.


Solution

  • Try this:

    function getLinks() {
      var doc=DocumentApp.getActiveDocument();
      var body=doc.getBody();
      for(var i=0;i<body.getNumChildren();i++) {
        var child=body.getChild(i);
        var attr=child.getAttributes();
        var linkUrl=attr.LINK_URL;
        if(linkUrl) {
          Logger.log('Child Index: %s linkUrl: %s text: %s',i,linkUrl,child.asText().getText());
        }
      }
    }