1

I would like to know if there is a way to highlight a specific word or body of text and insert a comment via some Google API. I realize there is an insert comment method of the drive API, however, the comment generated is for the entire document and not for just a specific part of the text.

Thanks so much.

dacardzmasta
  • 91
  • 1
  • 5

1 Answers1

0

So far I've been able to match and highlight all instances of the text "Earth" in my document (the search target string), but I'm still working on adding a comment. Here's the code to do that:

function myFunction() {
  var fileId = 'Id of your Document goes here';
  var background = background || '#FFFF00';  // highlight yellow.
  var target = 'Earth';
  var doc = DocumentApp.openById(fileId);
  var bodyElement = doc.getBody();
  var searchResult = bodyElement.findText(target);

  while (searchResult !== null) {
    var thisElement = searchResult.getElement();
    var thisElementText = thisElement.asText();

    //Logger.log(url);
    thisElementText.setBackgroundColor(searchResult.getStartOffset(), searchResult.getEndOffsetInclusive(),background);

    // search for next match
    searchResult = bodyElement.findText(target, searchResult);
  }
}

That is adapted/copied from here: Can I color certain words in Google Document using Google Apps Script? (technically I didn't adapt much because it's late, and I'm lazy). Still working on adding a comment. Since the key to this has been to isolate "elements" matching the target, I'd suspect just finding a method to add comments to an element and tagging that on to the end of the background coloring step would do it.

Community
  • 1
  • 1
thoughtcrime
  • 293
  • 3
  • 9