Google Apps Script :: Is It Possible To Get The Cursor Position Or Get The Selected Text From Google Document
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
Solution 1:
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
Solution 2:
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.
Solution 3:
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.';
}
}
Post a Comment for "Google Apps Script :: Is It Possible To Get The Cursor Position Or Get The Selected Text From Google Document"