I have a Google Apps Script that selects a range:
const editingRange = body.findText(needle);
if (editingRange) {
const range = doc.newRange();
range.addElement(editingRange.getElement().asText(),
editingRange.getStartOffset(),
editingRange.getEndOffsetInclusive())
doc.setSelection(range.build())
}
This works fine.
Now I'd like to select nothing (as if the user had just clicked somewhere in the document).
How do I do that?
doc.setSelection(null);
gives an error saying argument range cannot be null.
doc.setSelection(doc.newRange().build());
gives
Exception: Invalid argument: range at clearSelection7(argh:473:9)
I have scoured the docs https://developers.google.com/apps-script/reference/document/document without finding anything.
(I see getSelection
returns null
if there is no selection, you'd think setSelection
would then accept null
to select nothing, but no.)
On a whim I tried setting the cursor, and it worked! This seems to do the equivalent of a "select none":
export function clearHighlight() {
const doc = DocumentApp.getActiveDocument();
const paragraphs = doc.getBody().getParagraphs();
if(paragraphs) {
// just pick a position at the first element of the document
const pos = doc.newPosition(paragraphs[0].getChild(0), 0);
doc.setCursor(pos);
}
}
On the downside, even though this function seems to do nearly nothing, the script.google.com Executions log says it often takes over a second :(