App Script Google Docs Extension Selects Too Much Text

43 views Asked by At

The initial selection to identify the text is correct but the output isn't

The intention is for the extension to grab the selected text and pop it into a card search engine, then return the resulting webpage as a hyperlink attached to the selected text. The first half of that works fine however the printing seems to select the entirety of the paragraph instead of just the intended selected area. Is there a fix to this?

function websiteCall() {
  const hostText = getSelectedText();
  const linkage = searchFunction(cleanName(hostText));
  if (linkage) {
    Logger.log(linkage);
    DocumentApp.getActiveDocument().getSelection().getRangeElements()[0].getElement().asText().editAsText().setLinkUrl(linkage);
  }
}

I initially asked on stackOverflow a similar question which resulted in the final DocumentApp... line. However, it has the described problem and I wasn't able to catch it at the time due to how I use the script in my work.

1

There are 1 answers

0
Tanaike On BEST ANSWER

I believe your goal is as follows.

  • You want to set the hyperlink to the selected text. The text is part of a paragraph.

In your script, a whole paragraph is used. And, in your script, when a text is not selected, an error occurs. In this case, how about the following modification?

Modified script:

function websiteCall() {
  const hostText = getSelectedText();
  const linkage = searchFunction(cleanName(hostText));
  if (linkage) {
    Logger.log(linkage);
    const select = DocumentApp.getActiveDocument().getSelection();
    if (select) {
      const ele = select.getRangeElements()[0];
      ele.getElement().asText().editAsText().setLinkUrl(ele.getStartOffset(), ele.getEndOffsetInclusive(), linkage);
    }
  }
}
  • When you select a text of a part of a paragraph and run the script, the hyperlink of linkage is set to the selected text.

References: