You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

集成OpenAI API的Chrome扩展无法运行,控制台报错求助

Chrome扩展集成OpenAI API报错排查

问题现象

点击"Ask"按钮后,控制台出现两个错误:

  • Error handling response: TypeError: Cannot read properties of undefined (reading 'answer') at chrome-extension://enfpcdboapcobchgbmiiklnljabckpof/popup/popup.js:9:32
  • Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

代码清单

manifest.json

{
    "manifest_version": 3,
    "name": "GPT",
    "version": "1.0.0",
    "description": "OpenAI",
    "background": [{
        "matches": ["https://www.google.com/*"],
        "service_worker": ["background.js"],
        "persistent": true
    }],
    "action": {
        "default_popup": "popup/popup.html"
    },
    "icons": {
        "16": "images/icon-16.png",
        "32": "images/icon-32.png",
        "128": "images/icon-128.png"
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TrainerAI</title>
    <link rel="stylesheet" href="bulma.min.css">
</head>
<body>
    <div class="container m-3">
        <h1 class="title">TrainerAI</h1>
    </div>
    
    <div class="container m-3">
        <div class="field">
            <label class="label">Ask Anything</label>
            <div class="control">
                <input type="text" class="input" id="questionBox">
            </div>
        </div>
    </div>

    <div class="container m-3">
        <button class="button is-success is-fullwidth" id="askButton"> Ask </button>
    </div>

    <div class="container m-3">
        <div class="field">
          <label class="label">Result</label>
          <div class="control">
            <textarea class="textarea" id="resultBox" rows="10" readonly></textarea>
          </div>
        </div>
    </div>
</body>
<script src="popup.js"></script>
</html>
const questionBox = document.getElementById("questionBox");
const askButton = document.getElementById("askButton");
const resultBox = document.getElementById("resultBox");

// Send message to background.js on button click
askButton.addEventListener("click", () => {
  chrome.runtime.sendMessage({ question: questionBox.value }, (response) => {
    // Display response from background.js in resultBox
    resultBox.value = response.answer;
  });
});

background.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    // Check if the message is a question
    if (request.question) {
      const apiUrl = "https://api.openai.com/v1/completions";
      const apiKey = "";
      const model = "text-davinci-003";
      const prompt = `${request.question}
  
      fetch(apiUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${apiKey}`,
        },
        body: JSON.stringify({
          "model": model,
          "prompt": prompt,
          "max_tokens": 300, 
          "temperature": 0,
        }), 
      })
      .then(response => response.json())
      .then(data => {
        const answer = data.choices[0].text;
        console.log(answer)
        sendResponse({ answer: answer });
      })
      .catch(error => console.log(error));  
      return true;
    }
  });

错误原因及修复方案

1. 背景页配置格式错误(连接失败核心原因)

Manifest V3中background字段不能用数组包裹,且matches、persistent属性不适用于service_worker。修复后的manifest.json片段:

"background": {
    "service_worker": "background.js"
},

2. background.js字符串未闭合

prompt变量的模板字符串未用反引号闭合,导致语法错误,service_worker无法正常加载,造成"接收端不存在"的报错。修复后:

const prompt = `${request.question}`;

3. popup.js未处理空响应

直接访问response.answer会在请求失败时触发类型错误,添加判断逻辑:

askButton.addEventListener("click", () => {
  chrome.runtime.sendMessage({ question: questionBox.value }, (response) => {
    if (response && response.answer) {
      resultBox.value = response.answer;
    } else {
      resultBox.value = "请求失败,请检查控制台错误信息";
    }
  });
});

4. OpenAI API密钥未填写

background.js中apiKey为空字符串,需要填入你的OpenAI API密钥才能正常调用接口。

内容的提问来源于stack exchange,提问作者Marcuss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:17:04