1

I'm writing my first Google Apps Script and my goal is to automatically move the cursor to the last line of the document when it is opened. So far my function looks like this:

function onOpen(e) {
  var doc = DocumentApp.getActiveDocument();
  var paragraph = doc.getBody().appendParagraph('');
  var position = doc.newPosition(paragraph.getChild(0), 2);
  doc.setCursor(position);
}

and I'm basing my solution off of this documentation.

This script matches the documentation almost exactly. But when I open the document, nothing happens.

What might I be doing wrong?

This is my first experience with Javascript

Edit: This is different from this question -- my hope is to execute the script automatically when the document is opened.

At Ruben's suggestion, I checked View > Executions. Sure enough, the script is failing with the following error message:

Child index (0) must be less than the number of child elements (0). at onOpen(Code:4)
Jacob Stern
  • 3,758
  • 3
  • 32
  • 54
  • Check thread: [moving cursor to end of google document](https://stackoverflow.com/questions/45221103/how-do-i-move-the-cursor-to-the-end-of-the-document). – ross Apr 30 '19 at 13:24
  • 1
    Possible duplicate of [How do I move the cursor to the end of the document?](https://stackoverflow.com/questions/45221103/how-do-i-move-the-cursor-to-the-end-of-the-document) – ross Apr 30 '19 at 13:40

2 Answers2

2

Update:

Child index (0) must be less than the number of child elements (0). at onOpen(Code:4)

The above error message means that the appended paragraph hasn't childs

Try this

function onOpen(){
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var numChildren = body.getNumChildren();
  var pos = doc.newPosition(body.getChild(numChildren - 1),0);
  doc.setCursor(pos);
}


onOpen runs with a limited authorization level, meaning that onOpen can't do changes to the user interfase other than creating a menu. Maybe this is causing that you script do not work as you expected. To be sure, click on View > Executions and look for errors.
Rubén
  • 34,714
  • 9
  • 70
  • 166
0

The following code will goto the last character or to the first of the last child:

const onOpen = () => {
  const doc = DocumentApp.getActiveDocument()
  const body = doc.getBody()
  const kids = body.getNumChildren()
  const lastKid = body.getChild(kids - 1)
  let last = 0
  try {
    const lastPar = body.getChild(kids - 1).asParagraph()
    last = doc.newPosition(lastPar.getChild(0), lastPar.getText().length)
  } catch (e) {
    last = doc.newPosition(body.getChild(kids - 1), 0)    
  } finally {
    doc.setCursor(last)
  }
}
Jacob Jan Tuinstra
  • 1,197
  • 3
  • 19
  • 50