首页 > 解决方案 > 打开时移至 Google 文档的最后一行

问题描述

我正在编写我的第一个 Google Apps 脚本,我的目标是在打开文档时自动将光标移动到文档的最后一行。到目前为止,我的功能如下所示:

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

我的解决方案基于此文档

该脚本与文档几乎完全匹配。但是当我打开文档时,什么也没有发生。

我可能做错了什么?

这是我第一次使用 Javascript

编辑:这与这个问题不同——我希望在打开文档时自动执行脚本。

在 Ruben 的建议下,我检查了 View > Executions。果然,脚本失败并显示以下错误消息:

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

标签: javascriptgoogle-apps-scriptgoogle-docs

解决方案


更新:

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

上面的错误信息意味着附加的段落没有孩子

尝试这个

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 以有限的授权级别运行,这意味着除了创建菜单之外,onOpen 不能对用户界面进行更改。也许这会导致您的脚本无法按预期工作。可以肯定的是,单击 View > Executions 并查找错误。


推荐阅读