Search code examples
javascriptgoogle-apps-scriptgoogle-docs

Move to last line of Google Document when it is opened


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)

Solution

  • 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.