I’m trying to add comments to specific text in a Google Doc using Apps Script, but I’m stuck. I’ve got some code that creates comments, but they’re not anchored to any text. Here’s what I’ve tried:
function addComment() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.editAsText();
var start = 10;
var length = 5;
var comment = doc.addComment(text.getRange(start, start + length), 'This is a comment');
}
This adds a comment, but it’s not attached to any specific text. I’ve looked at the Google Drive API docs, but I’m not sure how to apply that to Apps Script. Has anyone successfully created text-anchored comments in Google Docs using code? Any tips or examples would be super helpful. Thanks!
I’ve encountered this issue before, and I found a solution that works well. Instead of using the addComment() method directly on the document, you need to use it on the specific range of text you want to anchor the comment to. Here’s a modified version of your code that should work:
function addAnchoredComment() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.editAsText();
var start = 10;
var length = 5;
var range = doc.newRange();
range.addElement(text, start, start + length - 1);
doc.addComment(range.build(), 'This is an anchored comment');
}
This approach creates a new range object, adds the specific text element to it, and then uses that range when adding the comment. This should anchor the comment to the selected text. Remember to adjust the start and length variables to target the desired text in your document.
I’ve been working on a similar project recently and found a workaround that might help you. Instead of relying solely on the DocumentApp methods, I switched to using the Google Drive API directly in Apps Script. I began by enabling the Drive API in the project, which allowed me to use the Drive.Comments.insert method to add comments with more control. The key was specifying the correct anchor in the request body to link the comment to the relevant text, along with retrieving the proper file ID and syntax for anchoring. Once I adjusted these details, the comments were anchored perfectly. If you need further details or a sample code snippet, feel free to ask.