afrologicinsect
afrologicinsect

Reputation: 171

Is there a way I can make this work in Google Apps Script

enter image description here

I have tried innerHTML instead of getBody() but still get an error, and any help with debugging on apps-script, mine does not seem to work.

 function findText(findme,colour,desc,rule_name) {
  var body = DocumentApp.getActiveDocument().getBody();
  var regExp = case_insensitive(findme);
  var foundElement = body.findText(regExp);
  while (foundElement != null) {
    var foundText = foundElement.getElement().asText();
    var start = foundElement.getStartOffset();
    var end = foundElement.getEndOffsetInclusive();
    foundText.setBackgroundColor(start, end, colour);
    number_oresults++;
    foundElement = body.findText(regExp, foundElement);
    var pusher = '<p><span style="background-color:'+colour+'"><b>'+rule_name+'</b> - '+ desc +'</span></p>';
    results.push(pusher);
   }
} 

Upvotes: 0

Views: 173

Answers (2)

Wicket
Wicket

Reputation: 38160

Sometimes the active methods when used in method chainging can throw errors like the one shown in your screenshot (`can't read property something of null) See Why Class Range getValues sometimes returns [[]] when chained to Class Sheet getActiveRange?

Try replacing

var body = DocumentApp.getActiveDocument().getBody();

by

var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();

It's worthy to note that DocumentApp.getActiveDocument() can only be used on bounded scripts and on standalone scripts when be executed as add-on either by using Run > Test as add-on... or by publishing the script as a G Suite Editor add-on for a Google Documents and executing the script from the UI.

NOTE: The following works fine on a standalone script executed Run > Test as add-on...

function onOpen(e) {
  DocumentApp.getUi()
  .createAddonMenu()
  .addItem('Test 1', 'doSomething1')
  .addItem('Test 2', 'doSomething2')
  .addToUi()
}

function doSomething1(){
  var body = DocumentApp.getActiveDocument().getBody();
  body.appendParagraph('Test 1');
}

function doSomething2(){
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  body.appendParagraph('Test 2');
}

Upvotes: 1

Diego
Diego

Reputation: 9571

Looks like you're running a standalone script, but DocumentApp.getActiveDocument() is only available in container-bound scripts.

You can copy-paste your script into a new script bound to that Google Doc or use one of the other open methods:

Upvotes: 1

Related Questions