How to set the cursor after a specific word in doc body in Google Docs through App Scripts?

146 Views Asked by At

I have a google docs created with App Script for which I am trying to place my cursor after a specific word in order to insert some content there.

When I just insert the content it inserts it at the end of the document. How can I find the specific word, set the cursor at the end of this word and then insert my content at this specific place ?

Please help me out !

1

There are 1 best solutions below

0
Emel On

You can achieve it by calling Document.getCursor(). A thing to note is that this only works in bound scripts.

A script can only access the cursor of the user who is running the script, and only if the script is bound to the document.

Here's the example from the documentation:

// Insert some text at the cursor position and make it bold.
var cursor = DocumentApp.getActiveDocument().getCursor();
if (cursor) {
  // Attempt to insert text at the cursor position. If the insertion returns null, the cursor's
  // containing element doesn't allow insertions, so show the user an error message.
  var element = cursor.insertText('ಠ‿ಠ');
  if (element) {
    element.setBold(true);
  } else {
    DocumentApp.getUi().alert('Cannot insert text here.');
  }
} else {
  DocumentApp.getUi().alert('Cannot find a cursor.');
}

Apps Script provides different ways to insert text, add a paragraph, insert text, add text ... It depends on the purpose of your script. In any case, you should check @Yuri's comment to better understand how Apps Script works.

Documentation