从 api 获得响应后无法在 twitter 字段中编辑响应

问题描述 投票:0回答:1
document.addEventListener('keydown', async function(event) {
  var target = event.target;

  //twitter

  if (target.tagName.toLowerCase() === 'div' && target.getAttribute('role') === 'textbox') {
    if (event.key === 'Enter') {
      var userInput = target.innerText;

      if (userInput.startsWith('/ai') && userInput.indexOf('/ai') === userInput.lastIndexOf('/ai')) {
        console.log('User input:', userInput);
        if (userInput) {
          const response = await fetch(`${API_URL}`, {
            method: "post",
            headers: {
              "Content-Type": "application/json",
              "Authorization": `Bearer ${key}`,
            },
            body: JSON.stringify({
              model: "text-davinci-003",
              prompt: userInput,
              max_tokens: 1000
            })
          });
          const data = await response.json();
          console.log(`OpenAI API response →`, data);
  
          const output = data.choices[0].text;
          target.innerText = output;
        }
        else {
          console.error("Error");
        }
      }
    }
  }});

所以我得到了 api 的响应,以完美地出现在 twitter 输入框中,但之后我无法编辑或修改输入字段中的 api 响应,这个浏览器扩展在其他网站上工作正常所以你们可以吗帮我这个?

我想在 api 响应进入 twitter 输入字段后修改 twitter 输入字段

javascript reactjs artificial-intelligence browser-extension
1个回答
0
投票

问题似乎与添加到 Twitter 输入字段的内容有关,这使得之后无法编辑。一个可能的原因是 innerText 属性被用来设置输入字段的内容,它可能会干扰输入字段的正常行为。

您可以尝试使用输入事件以编程方式设置输入字段的内容,这应该允许您之后编辑文本。以下是如何修改代码的示例:

document.addEventListener('keydown', async function(event) {
  var target = event.target;

  // Twitter
  if (target.tagName.toLowerCase() === 'div' && target.getAttribute('role') === 'textbox') {
    if (event.key === 'Enter') {
      var userInput = target.innerText;

      if (userInput.startsWith('/ai') && userInput.indexOf('/ai') === userInput.lastIndexOf('/ai')) {
        console.log('User input:', userInput);
        if (userInput) {
          const response = await fetch(`${API_URL}`, {
            method: "post",
            headers: {
              "Content-Type": "application/json",
              "Authorization": `Bearer ${key}`,
            },
            body: JSON.stringify({
              model: "text-davinci-003",
              prompt: userInput,
              max_tokens: 1000
            })
          });
          const data = await response.json();
          console.log(`OpenAI API response →`, data);
  
          const output = data.choices[0].text;

          // Trigger the input event to set the content of the input field
          const inputEvent = new InputEvent('input', {
            bubbles: true,
            cancelable: true,
          });
          target.textContent = output;
          target.dispatchEvent(inputEvent);
        }
        else {
          console.error("Error");
        }
      }
    }
  }
});

通过在设置内容后调度输入事件,您应该能够在添加 API 响应后编辑输入字段中的文本。

© www.soinside.com 2019 - 2024. All rights reserved.