javascriptgoogle-apps-scriptgoogle-docsgetselection

App Script Google Docs Extension Selects Too Much Text


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.


Solution

  • I believe your goal is as follows.

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

    References: