0

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 !

Harvey
  • 213
  • 1
  • 3
  • 12
  • 1
    Please provide your code – Waxim Corp Dec 21 '21 at 13:26
  • Docs: https://developers.google.com/apps-script/reference/document/position https://developers.google.com/apps-script/reference/document/document#newpositionelement,-offset https://developers.google.com/apps-script/reference/document/document#setcursorposition Example: https://stackoverflow.com/questions/68968735/google-apps-script-how-to-jump-forward-and-backward-between-footnote-numbers/69348678#69348678 – Yuri Khristich Dec 21 '21 at 15:51

1 Answers1

0

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
Emel
  • 2,283
  • 1
  • 7
  • 18