0

Is there any Google Apps Script API to get the cursor position or get the selected text from Google Document. I have searched for this and found nothing. If anyone knew about this case please help me.

Thanks, Vinod

Vinod Kumar
  • 75
  • 10

3 Answers3

0

Currently there is no such API. However, there is an open issue on the Issue Tracker. You can star this issue to register your interest and be notified to update to it

Srik
  • 7,907
  • 2
  • 20
  • 29
0

Try the following method Highlight and then select. It is definitely a work around, but it may suit your needs. A weakness of this method is that it will select all of the highlighted text of the specified color.

function findHighlighted() {
  var body = DocumentApp.getActiveDocument().getBody(),
      bodyTextElement = body.editAsText(),
      bodyString = bodyTextElement.getText(),
      char, len;

  for (char = 0, len = bodyString.length; char < len; char++) {
    if (bodyTextElement.getBackgroundColor(char) == '#ffff00') // Yellow
      Logger.log(bodyString.charAt(char))}
}

The previous answer is technically correct, in that a direct method for selecting text with mouse/cursor is not yet included in the API.

Community
  • 1
  • 1
Jacob Flatter
  • 171
  • 2
  • 11
  • I have checked this type of getting the selected text based on background color.But what I need is mouse selected text. Thanks for confirmation. – Vinod Kumar Jun 21 '13 at 11:05
0

The Add-ons quickstart has a sample with the following method:

/**
 * Gets the text the user has selected. If there is no selection,
 * this function displays an error message.
 *
 * @return {Array.<string>} The selected text.
 */
function getSelectedText() {
  var selection = DocumentApp.getActiveDocument().getSelection();
  if (selection) {
    var text = [];
    var elements = selection.getSelectedElements();
    for (var i = 0; i < elements.length; i++) {
      if (elements[i].isPartial()) {
        var element = elements[i].getElement().asText();
        var startIndex = elements[i].getStartOffset();
        var endIndex = elements[i].getEndOffsetInclusive();

        text.push(element.getText().substring(startIndex, endIndex + 1));
      } else {
        var element = elements[i].getElement();
        // Only translate elements that can be edited as text; skip images and
        // other non-text elements.
        if (element.editAsText) {
          var elementText = element.asText().getText();
          // This check is necessary to exclude images, which return a blank
          // text element.
          if (elementText != '') {
            text.push(elementText);
          }
        }
      }
    }
    if (text.length == 0) {
      throw 'Please select some text.';
    }
    return text;
  } else {
    throw 'Please select some text.';
  }
}
Fuhrmanator
  • 11,459
  • 6
  • 62
  • 111