Two Calls to Function, One Failing – Javascript – Chrome Extension

Hi I am working on my first chrome extension and am running into a problem when calling a function. I have a function that sends a prompt to the ChatGPT API and returns a value. When I call it this way:

// Execute if "Context Menu" from background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (
      message.type === "CM_SpellingGrammar" ||
      message.type === "CM_Task" ||
      message.type === "CM_Answer" ||
      message.type === "CM_WordCount" ||
      message.type === "CM_Rewrite" ||
      message.type === "CM_Clarity" ||
      message.type === "CM_Scholar" ||
      message.type === "CM_Tone" ||
      message.type === "CM_StructureOrganization"
     ) {
    CM_result = message.type;
    sendRetrieve();
  }
});

This is a call in my contentScript.js file using inputs from the Context Menu read from my background.js file.

However when I try to call the same function like this:

function TESTCLICKED(event) {
  CM_result = "CM_SpellingGrammar";
   sendRetrieve();
}

The request seems to be send to ChatGPT API but the console just returns “null”

Why is this happening? The function calls seem to be the same with the same inputs.

Here is my function to send a prompt to ChatGPT API:

function sendRetrieve() {
// If there's an active text input
if (
  document.activeElement &&
  (document.activeElement.isContentEditable ||
    document.activeElement.nodeName.toUpperCase() === "TEXTAREA" ||
    document.activeElement.nodeName.toUpperCase() === "INPUT")
) {
  // Set as original for later
  originalActiveElement = document.activeElement;
  // Use selected text or all text in the input
  textOriginal = 
    document.getSelection().toString().trim() ||
    document.activeElement.textContent.trim();
  text =
    document.getSelection().toString().trim() ||
    document.activeElement.textContent.trim();
} else {
  // If no active text input use any selected text on page
  textOriginal = document.getSelection().toString().trim();
  text = document.getSelection().toString().trim();
}
if (!text) {
  alert(
    "No text found. Select this option after right-clicking on a textarea that contains text or on a selected portion of text."
  );
  return;
}

console.log(originalActiveElement);


// SPECIAL CASES PROMPT
// Alter the message based on task from user for prompt
if (CM_result === "CM_SpellingGrammar") {
  text = "Revise the following for grammar and spelling:nn[" + text + "]nn If the provided text cannot be revised for spelling or grammar return 'NoneNullNoneNullNone'";
}  else if (CM_result === "CM_Task") {
    text = text;
} else if (CM_result === "CM_Answer") {
  text = "If the following is a question, answer it. Else return 'NoneNullNoneNullNone': [" + text + "]";
} else if (CM_result === "CM_WordCount") {
    var wordcountInput = prompt("Please provide a description of the word count adjustment you would like made:nnHint: It often helps to provide an upper and lower limit.");
    if (wordcountInput) {
      text = "Adjust the word count of the following based on 'Word count adjustment':nn[" + text + "]nnWord count adjustment: [" + wordcountInput + "]nn If you cannot complete this task return 'NoneNullNoneNullNone'";
    } else {
      return
    }
} else if (CM_result === "CM_Rewrite") {
  text = "Rewrite the following to convey the same meaning in different structure, words, and organization: [" + text + "]";
} else if (CM_result === "CM_Clarity") {
    text = "Revise the following for clarity:nn[" + text + "]";
} else if (CM_result === "CM_Scholar") {
  text = "Revise the following to meet the standards of an extremely scholarly written paragraph, up to the highest academic quality:nn[" + text + "]";
} else if (CM_result === "CM_Tone") {
  var toneInput = prompt("Please provide a tone description to complete the revisions:");
  if (toneInput) {
    text = "Adjust the tone of the following based on 'Desired tone':nn[" + text + "]nnDesired tone: [" + toneInput + "]nn If you cannot complete this task return 'NoneNullNoneNullNone'";
  } else {
    return
  }
} else if (CM_result === "CM_StructureOrganization") {
  text = "Revise the following for structure and organization:nn[" + text + "]";
}

// Define the prompt to send to the API
let userPrompt = {
  model: "gpt-3.5-turbo",
  messages: [{ role: "user", content: text }],
  temperature: 1,
};


document.body.style.cursor = "wait";

// Send a POST request to the endpoint with the prompt and headers
fetch(endpointUrl, {
  method: "POST",
  headers,
  body: JSON.stringify(userPrompt),
})
  .then((response) => response.json())
  .then((data) => {
    // Use original text element and fallback to current active text element
    const activeElement =
      originalActiveElement ||
      (document.activeElement.isContentEditable && document.activeElement);
    if (activeElement) {
      if (
        activeElement.nodeName.toUpperCase() === "TEXTAREA" ||
        activeElement.nodeName.toUpperCase() === "INPUT"
      ) {
        responseMessage = data.choices[0].message.content;
        console.log(responseMessage);


        // SPECIAL CASES RESPONSE
        // Dont add a period if the original prompt didn't end in one
        if ((
            CM_result === "CM_SpellingGrammar" || 
            CM_result === "CM_Rewrite") && 
            textOriginal.charAt(textOriginal.length - 1) !== "." && 
            responseMessage.charAt(responseMessage.length - 1) === "."
          ) {
          responseMessage = responseMessage.slice(0, -1);
        } 
        // Check for quotation marks and remove them
        if (
            responseMessage.charAt(0) === '"' &&
            responseMessage.charAt(responseMessage.length - 1) === '"'
          ) {
          responseMessage = responseMessage.slice(1, -1);
        }
        // Alert if CM_Answer prompt was not a question
        if (CM_result === "CM_Answer" && responseMessage.includes('NoneNullNoneNullNone')) {
          alert(
            "It appears the prompt provided was not a question. Try submitting a question."
          );
          document.body.style.cursor = "default";
          return;
        } 
        // Alert if CM_Tone prompt was not a valid tone
        if (CM_result === "CM_Tone" && responseMessage.includes('NoneNullNoneNullNone')) {
          alert(
            `It appears the provided tone could not be applied to the text or the prompt provided was not a valid tone. Try submitting a valid tone including but not limited to:nn${toneExamples}`
          );
          document.body.style.cursor = "default";
          return;
        } 
        // Alert if CM_WordCount prompt was not a valid tone
        if (CM_result === "CM_WordCount" && responseMessage.includes('NoneNullNoneNullNone')) {
          alert(
            "It appears the provided word count adjustment was invalid. Try submitting a valid word count adjustment description."
          );
          document.body.style.cursor = "default";
          return;
        } 
        // Alert if CM_GrammarSpelling prompt was not able to be corrected
        if (CM_result === "CM_SpellingGrammar" && responseMessage.includes('NoneNullNoneNullNone')) {
          alert(
            "It appears the prompt you provided was not able to be corrected for grammar or spelling. Please try a different prompt"
          );
          document.body.style.cursor = "default";
          return;
        } 
        // Insert Response
        if (CM_result === "CM_Answer") {
          activeElement.value = activeElement.value + "n" + responseMessage;
        } else {
          activeElement.value = responseMessage;
        }



      }
    } else {
      // Alert reply since no active text area
      alert(`ChatGPT says: ${data.reply}`);
    }

    document.body.style.cursor = "default";
  })
  .catch((error) => {
    console.error(error);
    document.body.style.cursor = "default";
  });
}