打开文档时移动到 Google 文档的最后一行
Move to last line of Google Document when it is opened
我正在编写我的第一个 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);
}
我的解决方案基于 this documentation。
此脚本与文档几乎完全匹配。但是当我打开文档时,没有任何反应。
我可能做错了什么?
这是我第一次使用 Javascript
编辑: 这与不同--我希望在打开文档时自动执行脚本。
根据 Ruben 的建议,我检查了视图 > 执行。果然,脚本失败并显示以下错误消息:
Child index (0) must be less than the number of child elements (0). at onOpen(Code:4)
更新:
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 除了创建菜单外不能对用户界面进行更改。也许这导致您的脚本无法按预期工作。可以肯定的是,单击“查看”>“执行”并查找错误。
以下代码将转到最后一个字符或最后一个字符的第一个 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)
}
}
我正在编写我的第一个 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);
}
我的解决方案基于 this documentation。
此脚本与文档几乎完全匹配。但是当我打开文档时,没有任何反应。
我可能做错了什么?
这是我第一次使用 Javascript
编辑: 这与
根据 Ruben 的建议,我检查了视图 > 执行。果然,脚本失败并显示以下错误消息:
Child index (0) must be less than the number of child elements (0). at onOpen(Code:4)
更新:
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 除了创建菜单外不能对用户界面进行更改。也许这导致您的脚本无法按预期工作。可以肯定的是,单击“查看”>“执行”并查找错误。
以下代码将转到最后一个字符或最后一个字符的第一个 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)
}
}