如何在Google Chrome扩展中调用ChatGPT API?求具体实现方法
开发调用ChatGPT API的Chrome扩展实现步骤
一、前期准备
- 注册OpenAI账号并获取API密钥:登录OpenAI官方平台,进入API密钥管理页面创建新密钥,务必妥善保存密钥,不要泄露。
- 了解Chrome扩展V3版本的基础结构:核心文件包括
manifest.json(配置文件)、前端页面(如popup.html)、逻辑脚本(如popup.js)。
二、搭建扩展基础结构
创建项目文件夹,包含以下核心文件:
1. manifest.json(V3版本配置)
{ "manifest_version": 3, "name": "ChatGPT Chrome扩展", "version": "1.0", "description": "调用ChatGPT API的Chrome扩展", "action": { "default_popup": "popup.html", "default_icon": { "16": "icons/icon16.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } }, "permissions": ["storage", "activeTab"], "host_permissions": ["https://api.openai.com/*"] }
- 注意:
host_permissions必须声明OpenAI API的域名,确保扩展能发起跨域请求;storage权限用于存储用户的API密钥(可选,也可让用户每次输入)。
2. popup.html(扩展弹窗界面)
<!DOCTYPE html> <html> <head> <style> body { width: 350px; padding: 15px; } #apiKey { width: 100%; margin-bottom: 10px; padding: 8px; } #prompt { width: 100%; height: 80px; margin-bottom: 10px; padding: 8px; } #submitBtn { width: 100%; padding: 10px; background: #10a37f; color: white; border: none; border-radius: 4px; cursor: pointer; } #result { margin-top: 15px; padding: 10px; border: 1px solid #eee; border-radius: 4px; min-height: 50px; } </style> </head> <body> <input type="password" id="apiKey" placeholder="输入你的OpenAI API密钥"> <textarea id="prompt" placeholder="输入你的问题..."></textarea> <button id="submitBtn">发送请求</button> <div id="result"></div> <script src="popup.js"></script> </body> </html>
三、实现API调用逻辑(popup.js)
document.getElementById('submitBtn').addEventListener('click', async () => { const apiKey = document.getElementById('apiKey').value.trim(); const prompt = document.getElementById('prompt').value.trim(); const resultDiv = document.getElementById('result'); if (!apiKey || !prompt) { resultDiv.textContent = "请填写API密钥和问题"; return; } resultDiv.textContent = "正在请求中..."; try { const response = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }, body: JSON.stringify({ model: "gpt-3.5-turbo", messages: [{role: "user", content: prompt}] }) }); if (!response.ok) { throw new Error(`请求失败:${response.statusText}`); } const data = await response.json(); resultDiv.textContent = data.choices[0].message.content.trim(); } catch (error) { resultDiv.textContent = `错误:${error.message}`; } });
- 核心说明:
- 使用
fetch发起POST请求到OpenAI的Chat Completions API端点; - 请求头需携带API密钥的
Authorization字段; - 请求体指定模型(如
gpt-3.5-turbo)和用户提问内容; - 处理响应并将结果展示在弹窗中,同时捕获异常并提示错误。
- 使用
四、测试与发布
- 本地测试:打开Chrome浏览器,进入
chrome://extensions/,开启"开发者模式",点击"加载已解压的扩展程序",选择项目文件夹即可加载测试。 - 打包发布:在
chrome://extensions/中点击"打包扩展程序",生成.crx文件,可上传至Chrome应用商店发布(需完成开发者注册)。
内容的提问来源于stack exchange,提问作者Youqiang Xiong
相关产品推荐
相关产品推荐

