I am writing a script of Google Apps Script with my Google Document and wondering how to move the cursor to the very beginning of the document. What I was trying to do at the end is just replace the first line with some string.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
This is very simple, you can use the setCursor()
method documented here.
Example code :
function setCursorToStart() {
var doc = DocumentApp.getActiveDocument();
var paragraph = doc.getBody().getChild(0);
var position = doc.newPosition(paragraph.getChild(0), 0);
doc.setCursor(position);
}
This will set the cursor position to the start of your document but in your question you say you want to insert some data at this position, then the actual cursor position is irrelevant, you can insert a string there without necessarily moving the cursor . Example code :
function insertTextOnTop() {
var doc = DocumentApp.getActiveDocument();
var top = doc.getBody().getChild(0);
top.asParagraph().insertText(0,'text to insert');
doc.saveAndClose();
}