Google Script Lesson 7 – Modifying a Google Doc

In this example we get into the real power of Google Scripts: the ability to interact with Google Docs, Sheets, and more.

Click here to view the Example Script 07 – Modifying a Google Doc.

function myFunction() {
  /*  The array, data, has three values: studentEmail, message, and docId
  var data = ["","Johnny is doing well in school.","15tVeiwdHrhKJQuSpYknJC4CG1-oPlhhqyZNxcMcZro8"]
  var studentEmail = data[0];
  var message = data[1];
  var docId = data[2];
  addMessage(studentEmail, message, docId);

Notice that there is an additional value in the data array, a docId. This is the unique identifying code that marks each Google Doc, and can be found in the address bar at the top of the screen. The id for the Script file, for example, is “197QPA5_gYblBqHM6xn1tN9adfW9BCnJ87m4YfO63GYhKXebW5sTnWafD”. It is the long alphanumeric sequence in between forward slashes.

In this example, the teacher feedback is appended to a Google Text Doc. I have used the docId of a Text Doc that I created for demo purposes, but you can create your own Google Doc, find the code, and insert that code instead of mine as the value in the ‘data’ array.

Here’s the second half of the program, the ‘addMessage’ function:

function addMessage(studentEmail, message, docId) {

var timeStamp = new Date();
message = timeStamp + "\nHere is your feedback:\n" + message + "\n\nRegards, \nMr Jones\n";

var doc = DocumentApp.openById(docId);
var body = doc.getBody();

In the addMessage function, we see what we can do with this id. After we add our timeStamp to the message, we’re going to use the Google Service called DocumentApp.  First we call on the DocumentApp object, which can do lots of things. To see what it can do, make a copy of the script file, then type DocumentApp followed by a period ‘.’

This will list all of the METHODS that this object can call. Many of them will also RETURN a value. In a sense, it is a way of starting with the very general, then going to the specific.

  • We are taking the DocumentApp and returning a document we are calling ‘doc’.
  • Then we are calling a method on ‘doc’ and returning the text body as a variable called ‘body’.
  • Next, we are calling a method on ‘body’ and telling it to add our ‘message’ variable to it.
  • Finally, we are forcing an update to the doc so that all of the changes are updated.

CHALLENGE: add an additional message to the one presented in this example. Say whatever you want, and then check to see if it was appended to the Text Doc.

Leave a comment

Your email address will not be published. Required fields are marked *