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

Chrome扩展调用OpenAI API遇JSON解析错误及输出undefined问题

Chrome扩展调用OpenAI API报错:无法解析请求JSON体且输出undefined

问题描述

我正在开发一款Chrome扩展,功能是提取网页文本并发送给ChatGPT,但调用API时收到错误提示:

"We could not parse the JSON body of your request."

同时最终输出结果为undefined。扩展的HTML和CSS部分运行正常,我的JS代码如下:

document.addEventListener('DOMContentLoaded', function () {
var getBattleCardButton = document.getElementById('get-battle-card-button');
getBattleCardButton.addEventListener('click', function () {
    // Get all the content on the page as a string
    var pageContent = document.body.innerText;

    // Truncate the content to a maximum length of 4096 tokens
    var truncatedContent = pageContent.substring(0, 4096);

    // Construct the prompt by concatenating the specific words with the page content
    var prompt = "Summarize this content into 3 sections, What? Why? and How?. Each section with 3 concise points. " + truncatedContent;

    // Send the page content to Chat GPT as a prompt
    fetch('https://api.openai.com/v1/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer MY_API_KEY'
        },
        body: JSON.stringify({
            'prompt': prompt,
            'model': 'text-davinci-003',
            'max_tokens': 512
        })
    })
        .then(response => response.json())
        .then(data => {
            // Open a new tab and insert the Chat GPT output into it
            var newTab = window.open();
            newTab.document.body.innerHTML = data.response;
        })
        .catch(error => {
            console.error('Error:', error);
        });
});
});

解决方案

1. 修复JSON请求体解析失败问题

  • 核心错误:直接拼接网页文本到prompt时,文本中可能包含引号、反斜杠等JSON特殊字符,导致JSON.stringify生成的JSON格式非法;另外你用substring(0, 4096)按字符数截断,和OpenAI的token计数逻辑不匹配,且未预留prompt前缀的字符空间,容易导致prompt过长。
  • 修复代码:
    // 预留足够空间给prompt前缀,按字符数截断(若要精确token计数需引入tiktoken库)
    var truncatedContent = pageContent.substring(0, 3000);
    // 转义文本中的特殊JSON字符,同时去掉JSON.stringify自动添加的首尾引号
    var escapedContent = JSON.stringify(truncatedContent).slice(1, -1);
    var prompt = "Summarize this content into 3 sections, What? Why? and How?. Each section with 3 concise points. " + escapedContent;
    

2. 修复输出结果为undefined的问题

  • 核心错误:OpenAI Completions API的响应内容并不在data.response字段,而是存储在data.choices[0].text中,直接访问data.response会返回undefined。
  • 修复代码:
    .then(data => {
        var newTab = window.open();
        // 获取并清理返回的文本(去掉首尾空白)
        newTab.document.body.innerHTML = data.choices[0].text.trim();
    })
    

3. 额外必须注意的事项

  • CORS限制:Chrome扩展的内容脚本直接调用OpenAI API会触发跨域限制,建议将API调用逻辑移至后台脚本(background.js),通过消息传递机制让内容脚本和后台脚本交互。
  • API密钥安全:绝对不要将API密钥硬编码在前端代码中,这会导致密钥泄露。正确做法是让用户在扩展设置中输入密钥,并使用Chrome.storage API加密存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:20:47