Search code examples
javascriptgoogle-apps-scriptgoogle-docsgoogle-docs-api

Google Script - findText is not defined


I'm trying to make a script for my Google document so I can format specific paragraphs in some "chat log" segments according to the nickname the paragraph begins with (example: "myNickname: blah blah blah").

I made a test function to test out findText() but when I execute test(), it returns this error: ReferenceError: findText is not defined test @ Code.gs:21

Here is the complete script:

function onOpen(e) {
  DocumentApp.getUi()
  .createMenu("FORMATTING")
    .addItem("Test", "test")

  .addToUi();
}

function formatNickname(nickname, style) {
  nickname = nickname + ":"; // Dialogue is in a 'chat log' format, so it's displayed as "NICKNAME: Blah blah blah"

  let foundText = findText(nickname); 

  foundText.getText().setTextStyle(style);

  console.log(foundText); // Debug
}

function test() {
  formatNickname("BAB", findText("AA:").getText.getTextStyle()); // The second parameter is for debug reasons. AA is a character with a specific text style.
}

And here is my appsscript.json:

{
  "oauthScopes": [
    "https://www.googleapis.com/auth/documents.currentonly",
    "https://www.googleapis.com/auth/documents"
  ],
  "timeZone": "America/Sao_Paulo",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}

I have Google Apps Script API turned on in my user settings, as instructed in this answer.


Solution

  • findText is not a global function, you can only call it when you have a Text element selected. You have to first obtain the current Document using getActiveDocument() (or other ways as long as you have access), then perform your search from that document.

    In addition, getTextStyle() and setTextStyle() only exists in Sheets but not Docs, you have to use getAttributes() and setAttributes() for that instead. I have personally try to setup and run myself and here's a working code example to copy the style of one text element to another:

    function onOpen(e) {
      DocumentApp.getUi()
        .createMenu("FORMATTING")
        .addItem("Test", "test")
        .addToUi();
    }
    
    function formatNickname(text, nickname, attributes) {
      nickname = nickname + ":"; // Dialogue is in a 'chat log' format, so it's displayed as "NICKNAME: Blah blah blah"
      const foundText = text.findText(nickname).getElement().asText();
      foundText.setAttributes(attributes);
    }
    
    function test() {
      const body = DocumentApp.getActiveDocument().getBody();
      const text = body.editAsText();
      formatNickname(text, "BAB", text.findText('AA:').getElement().asText().getAttributes()); // The second parameter is for debug reasons. AA is a character with a specific text style.
    }