title: Google Apps Script. Get all links from document
body: <p>Hi all) I need to get all links from google document. I found that general approach:</p>
  
  <pre><code>function getAllLinks(element) {
    var links = [];
    element = element || DocumentApp.getActiveDocument().getBody();
  
    if (element.getType() === DocumentApp.ElementType.TEXT) {
      var textObj = element.editAsText();
      var text = element.getText();
  
      Logger.log("text " + text);
  
      var inUrl = false;
      for (var ch=0; ch &lt; text.length; ch++) {
        var url = textObj.getLinkUrl(ch);
        if (url != null) {
          if (!inUrl) {
            // We are now!
            inUrl = true;
            var curUrl = {};
            curUrl.element = element;
            curUrl.url = String( url ); // grab a copy
            curUrl.startOffset = ch;
          }
          else {
            curUrl.endOffsetInclusive = ch;
          }          
        }
        else {
          if (inUrl) {
            // Not any more, we're not.
            inUrl = false;
            links.push(curUrl);  // add to links
            curUrl = {};
          }
        }
      }
    }
    else {
      var numChildren = element.getNumChildren();
      for (var i=0; i&lt;numChildren; i++) {
        links = links.concat(getAllLinks(element.getChild(i)));
      }
    }
  
    Logger.log(links);
  }
  </code></pre>
  
  <p>It works perfectly fine if i, for example, type url in text, but if add link via menu ("Insert" -> "Link") it doesn't work, function <code>getLinkUrl()</code> returns <code>null</code>. Documentation contains info about <a href="https://developers.google.com/apps-script/reference/slides/link" rel="nofollow noreferrer">Link</a> class, i thought all links represented by it, but don't understand why i can't get link inserted via menu.</p>
  
  <p>I thought maybe i can use some regular expression on text of document element, but if i add link via menu item i can specify custom label for link, which may not contain url in it.</p>
  
  <p>Have anyone faced this scenario? What i missed?</p>