0

I am working on a large project in google docs and would like to be able to be able to have a custom menu item in where I can put the word (for example Target) which I want all instances linked to something (in my case linked to the appropriate header within the document).

The end goal is to be able to quickly link all instances of a word to the appropriate section of the document. I can do this one at a time but with the already large size of the document doing it like that is not practical.

Below is the link of a bit of code (under CODE section) I found which seems like it should be able to search for the unlinked instances of a word and link them but I would like to make it useable via a menu item where I can put in the new word I want linked and then the appropriate link.

How to find a Word in a Document and insert a url

  • If you already have the code then what's the problem – Cooper May 13 '23 at 18:37
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community May 16 '23 at 01:59

1 Answers1

0

To avoid multiple prompts I have developed a simple example using a custom dialog to get the text and url and then apply a link to every text that matches in the doc.

Code.gs

function onOpen(e) {
  DocumentApp.getUi().createMenu("My Menu")
      .addItem("Add Line","addLink")
      .addToUi();
}

function addLink() {
  try {
    let html = HtmlService.createHtmlOutputFromFile("HTML_AddLink");
    html.setHeight(200);
    html.setWidth(200);
    DocumentApp.getUi().showModalDialog(html,"Add Link");
  }
  catch(err) {
    DocumentApp.getUi().alert(err);
  }
}

function setLink(text,link) {
  try {
    let doc = DocumentApp.getActiveDocument();
    let body = doc.getBody();
    let find = body.findText(text);
    while( find ) {
      let element = find.getElement().asText();
      element.setLinkUrl(find.getStartOffset(),find.getEndOffsetInclusive(),link);
      find = body.findText(text,find);
    }
  }
  catch(err) {
    Logger.log(err);
  }
}

HTML_AddLink.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <label for="linkText">Search Text</label></br>
    <input id="linkText" type="text"><br><br>
    <label for="linkURL">Link URL</label></br>
    <input id="linkURL" type="text>"></br><br>
    <input id="linkButton" type="button" value="Submit" onclick="buttonOnClick()">
    <script>
      function buttonOnClick() {
        try {
          let text = document.getElementById("linkText").value;
          let link = document.getElementById("linkURL").value;
          google.script.run.setLink(text,link);
          google.script.host.close();
        }
        catch(err) {
          alert(err);
        }
      }
    </script>
  </body>
</html>

References

TheWizEd
  • 7,517
  • 2
  • 11
  • 19