How to programmatically add text-anchored comments in Google Docs?

I’m trying to add comments tied to specific text in a Google Doc using Apps Script. But I can’t get it to work right. Here’s what I’ve tried:

function addAnchoredComment() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var text = body.editAsText();
  
  var startIndex = 10;
  var endIndex = 20;
  var commentText = 'This is a test comment';
  
  var position = doc.newPosition(text, startIndex);
  var comment = doc.addComment(position, commentText);
  
  // Trying to set the range, but it's not working
  comment.setAnchor(doc.newRange(
    doc.newPosition(text, startIndex),
    doc.newPosition(text, endIndex)
  ));
}

The comment shows up, but it’s not attached to any specific text. It just floats at the top of the document. What am I doing wrong? Is there a way to make this work with Apps Script? Or do I need to use a different API? Any help would be awesome!

hey isaac, i’ve run into this too. the apps script api can be a pain for comments. have u tried using the docs api instead? it’s way more reliable for this kinda stuff. u’ll need to enable it in ur project settings first tho. lemme know if u want me to share some sample code that works!

As someone who’s worked extensively with Google Docs API, I can tell you that anchoring comments programmatically can be a bit finicky. One thing I’ve found that works well is using the Advanced Docs Service instead of the built-in DocumentApp.

Here’s a snippet that’s worked for me:

function addAnchoredComment() {
  var docId = DocumentApp.getActiveDocument().getId();
  var requests = [{
    'createComment': {
      'text': 'This is a test comment',
      'range': {
        'startIndex': 10,
        'endIndex': 20
      }
    }
  }];
  
  Docs.Documents.batchUpdate({'requests': requests}, docId);
}

Make sure to enable the Advanced Docs Service in your script project first. This method gives you more control and reliability when it comes to comment placement. It’s been a game-changer for my document automation tasks.

I’ve encountered this issue before, and it can be tricky. The problem lies in how Google Docs handles comment anchoring through Apps Script. Instead of using setAnchor(), try creating a new comment with a range directly:

function addAnchoredComment() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var text = body.editAsText();
  
  var startIndex = 10;
  var endIndex = 20;
  var commentText = 'This is a test comment';
  
  var range = doc.newRange(
    doc.newPosition(text, startIndex),
    doc.newPosition(text, endIndex)
  ).build();
  
  doc.addComment(range, commentText);
}

This approach should anchor the comment to the specified text range. Remember that indices are zero-based, so adjust accordingly. If you’re still having issues, double-check that your indices are within the document’s content bounds.