How to add linked comments to text selections in Google Docs via Apps Script

I’m trying to use Apps Script to add comments that link to specific text portions in a Google Document, but I can’t get it working properly.

I found some info in the Google Drive API docs about making comments with anchors, so I wrote this code to test it:

Drive.Comments.insert({
  "kind": "drive#comment",
  "author": {
    "kind": "drive#user",
    "displayName": EMAIL_ADDRESS,
    "isAuthenticatedUser": true,
  },
  "content": MESSAGE_TEXT,
  "status": "open",
  "anchor": "{'r':"
             + DOC_REVISION
             + ",'a':[{'txt':{'o':"
             + START_POSITION
             + ",'l':"
             + TEXT_LENGTH
             + ",'ml':"
             + DOCUMENT_LENGTH
             + "}}]}", 
  "fileId": DOCUMENT_ID
}, DOCUMENT_ID);

/* EMAIL_ADDRESS, MESSAGE_TEXT, DOC_REVISION, DOCUMENT_ID: string,
   START_POSITION, TEXT_LENGTH, DOCUMENT_LENGTH: int */

The comment gets created and shows up in the document, but it doesn’t attach to the text I’m targeting with START_POSITION and TEXT_LENGTH. I double checked that I’m using the right revision ID since the docs mention that’s important.

What am I missing to make the comment actually link to the selected text?

Yeah, anchor JSON is a pain - you’re missing quotes around the keys. Try this: “anchor”: “{"r":"” + DOC_REVISION + “","a":[{"txt":{"o":” + START_POSITION + “,"l":” + TEXT_LENGTH + “}}]}” The escaping sucks but it fixed the same problem for me.

Had the same problem with Drive API comments - it’s usually character encoding issues. You need to encode the anchor string properly, especially with special characters or non-ASCII text. Your code looks fine, but try wrapping the anchor string in encodeURIComponent() before the API call. Also check if your START_POSITION calculation handles paragraph breaks right - they count as characters and mess up positioning. I wrote a helper function to validate character positions against the actual document before creating comments. Document API is way more reliable, but if you’re stuck with Drive API for permissions, the encoding fix should solve your anchor problem.

Hit this exact problem last year building a document review tool. Drive API comments with anchors are unreliable in Apps Script - the text selection linking just doesn’t work consistently. Your anchor format looks right, but Google’s implementation is buggy. What fixed it for me: switch to Document API instead. Use DocumentApp.openById() to grab the document, then newPosition() and newRange() to create proper text ranges, and addComment() on those ranges. Comments actually stick to the text selections this way. The big difference? DocumentApp handles text positioning internally - you don’t have to mess with anchor JSON manually. Your START_POSITION and TEXT_LENGTH values should work fine, just convert them to Document API range format.