How to block message submission on “Enter” key in a ChatGPT function while using addEventListeners?

I am developing a Chrome extension that intercepts messages sent to ChatGPT and processes them before allowing submission. My goal is to block message submission when the “Enter” key is pressed unless a certain condition is met (handled by an asynchronous shouldProceedComponent function).

function addEventListeners(
  textarea: HTMLTextAreaElement | null,
  button: HTMLButtonElement | null
): void {
  textarea?.addEventListener('keydown', (event) => {
    void (async () => {
      if (event.isTrusted && event.code === 'Enter' && !event.shiftKey) {
        // Stop the event from propagating
        event.stopPropagation();
        event.preventDefault();
        
        const proceed = await shouldProceedComponent(textarea);
        if (proceed) {
          button?.click();
          chrome.runtime.sendMessage({ detections: 0 });
        }
      }
    })();
  });
}

Issue:

When pressing “Enter,” the message submission gets blocked as expected, but the button’s click event doesn’t always trigger as intended. Additionally, I’m not sure if event.stopPropagation() and event.preventDefault() are correctly applied to ensure proper functionality.

What I have tried:

  1. Debugging the asynchronous shouldProceedComponent function to confirm it returns the expected value.
  2. Checking if event.isTrusted is true to prevent artificial events from being handled.
  3. Using event.stopPropagation() and event.preventDefault() to block the default behavior of the “Enter” key.

Question:
How can I reliably block message submission by pressing “Enter” while properly ensuring the button click event triggers if the shouldProceed function returns true?

Any guidance or suggestions would be greatly appreciated!