Get user-selected text

2020-02-26 11:00发布

I want to select words or lines by mouse in a Google Doc, and by script, get these selected words or lines.

Example:

  var doc = DocumentApp.getActiveDocument();
  var docText = doc.editAsText();
  var text = docText.getSelection();

I tried, but I didn't find any methods for selection access like in VBA.

5条回答
何必那么认真
2楼-- · 2020-02-26 11:48
function getHighlightedText() {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
  var elements = selection.getRangeElements();
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    // Only modify elements that can be edited as text; skip images and other non-text elements.
    if (element.getElement().editAsText) {
      var text = element.getElement().editAsText();
      return text;
    }
  }
}
}
查看更多
对你真心纯属浪费
3楼-- · 2020-02-26 11:51

If you want to retrieve text you've highlighted, could try...

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))}
}

Derived from Jonathan's I/O example. However, note that working with cursor position and selections is not yet available as of this writing.

UPDATE: Cursor selection is available now, see docs.

查看更多
手持菜刀,她持情操
4楼-- · 2020-02-26 12:02

To add to Bryan's answer I wrote this to convert the individual characters to return an array of words or phrases that have been highlighted.

   function findHighlighted() {
    var results = [];
    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) !== null)
                    results.push([char, bodyString.charAt(char)]);
    }
    return results;
}

function getWords() {
    var arr = findHighlighted();
    var wordList = [];
    var holding = [];
    var nextNum, sum;
    for (var i = 0; i < arr.length; i++) {
            if (arr[i + 1] === undefined) {
                    nextNum = 0;
            } else {
                    nextNum = arr[i + 1][0];
            }
            sum = (Number(arr[i][0]) + 1);
            if (nextNum === sum) {
                    holding.push(arr[i][1]);
            } else {
                    holding.push(arr[i][1]);
                    wordList.push(holding.join(""));
                    holding = [];
            }
    }
    Logger.log(wordList);
}
查看更多
Evening l夕情丶
5楼-- · 2020-02-26 12:03

The ability to work with cursor position and selected text was added yesterday, addressing Issue 2865: Get current user location & state information in Document. See the blog post as well.

It turns out that there are some tricks to working with selections. I've tried to show them here - please add comments if you find any others, I'll gladly update.

function onOpen() {
  DocumentApp.getUi().createMenu('Selection')
    .addItem("Report Selection", 'reportSelection' )
    .addToUi();
}

function reportSelection () {
  var doc = DocumentApp.getActiveDocument();
  var selection = doc.getSelection();
  var ui = DocumentApp.getUi();

  var report = "Your Selection: ";

  if (!selection) {
    report += " No current selection ";
  }
  else {
    var elements = selection.getSelectedElements();
    // Report # elements. For simplicity, assume elements are paragraphs
    report += " Paragraphs selected: " + elements.length + ". ";
    if (elements.length > 1) {
    }
    else {
      var element = elements[0].getElement();
      var startOffset = elements[0].getStartOffset();      // -1 if whole element
      var endOffset = elements[0].getEndOffsetInclusive(); // -1 if whole element
      var selectedText = element.asText().getText();       // All text from element
      // Is only part of the element selected?
      if (elements[0].isPartial())
        selectedText = selectedText.substring(startOffset,endOffset+1);

      // Google Doc UI "word selection" (double click)
      // selects trailing spaces - trim them
      selectedText = selectedText.trim();
      endOffset = startOffset + selectedText.length - 1;

      // Now ready to hand off to format, setLinkUrl, etc.

      report += " Selected text is: '" + selectedText + "', ";
      report += " and is " + (elements[0].isPartial() ? "part" : "all") + " of the paragraph."
    }
  }
  ui.alert( report );
}
查看更多
等我变得足够好
6楼-- · 2020-02-26 12:04

You are close. I think you want the findText() method.

var text = docText.findText("some string of text in the document") // for example

I'm not familiar with VBA, but this will work to select text in a doc.

查看更多
登录 后发表回答