我们以chatgpt为例,ollama的api也是兼容chatgpt的。
创建一个 Chrome 插件来实现网页中选择文本进行 AI 问答,并调用 ChatGPT 的 API 接口,涉及以下步骤:
步骤概述:创建 Chrome 插件结构:包括 manifest.json、popup.html、popup.js 等文件。设置权限:确保插件有权限访问当前页面的内容和调用外部 API。与页面交互:允许用户选择页面上的文本。调用 ChatGPT API:使用 HTTP 请求发送选择的文本,并获取 AI 回答。显示结果:将 AI 回答显示在插件的弹出窗口中。具体实现步骤:1. 创建 manifest.json 文件{ "manifest_version": 3, "name": "ChatGPT Q&A Plugin", "version": "1.0", "description": "Select text on a webpage and get AI answers using ChatGPT API.", "permissions": [ "activeTab", "storage", "http://*/*", "https://*/*" ], "action": { "default_popup": "popup.html", "default_icon": { "16": "icon16.png", "48": "icon48.png", "128": "icon128.png" } }, "icons": { "16": "icon16.png", "48": "icon48.png", "128": "icon128.png" }, "background": { "service_worker": "background.js" }, "permissions": [ "activeTab" ] }2. 创建 popup.html 文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ChatGPT Q&A</title> <script src="popup.js"></script> <style> body { width: 300px; padding: 10px; } button { margin-top: 10px; } </style> </head> <body> <h2>ChatGPT Q&A</h2> <textarea id="selectedText" rows="4" cols="30" placeholder="Select text on the webpage"></textarea> <button id="askButton">Ask</button> <div id="answer"></div> </body> </html>3. 创建 popup.js 文件
document.addEventListener('DOMContentLoaded', function () { const askButton = document.getElementById('askButton'); const selectedText = document.getElementById('selectedText'); const answerDiv = document.getElementById('answer'); askButton.addEventListener('click', function () { chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { const tab = tabs[0]; chrome.scripting.executeScript({ target: { tabId: tab.id }, function: getSelectedText }, function (results) { const selected = results[0].result; if (selected) { fetchChatGPTResponse(selected) .then(response => response.json()) .then(data => { if (data && data.answer) { answerDiv.textContent = data.answer; } else { answerDiv.textContent = 'No answer found.'; } }) .catch(error => { answerDiv.textContent = 'Error fetching answer.'; console.error('Error fetching answer:', error); }); } else { answerDiv.textContent = 'No text selected.'; } }); }); }); function getSelectedText() { const selection = window.getSelection(); return selection.toString().trim(); } async function fetchChatGPTResponse(text) { const apiUrl = 'YOUR_CHATGPT_API_ENDPOINT'; // Replace with your ChatGPT API endpoint const apiKey = 'YOUR_API_KEY'; // Replace with your API key const requestBody = { text: text, model: 'gpt-3.5-turbo', // Adjust the model according to your ChatGPT setup max_tokens: 100 }; const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }; const response = await fetch(apiUrl, { method: 'POST', headers: headers, body: JSON.stringify(requestBody) }); return response; } });4. 创建 background.js 文件(用于监听页面选择文本)
chrome.contextMenus.create({ id: 'chatgptQnA', title: 'Ask with ChatGPT', contexts: ['selection'], onclick: function (info, tab) { chrome.tabs.sendMessage(tab.id, { action: 'getSelection' }); } }); chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { if (message.action === 'sendSelection') { fetchChatGPTResponse(message.selection) .then(response => response.json()) .then(data => sendResponse(data)) .catch(error => sendResponse({ error: error })); return true; // To indicate that we will send response asynchronously } }); async function fetchChatGPTResponse(text) { const apiUrl = 'YOUR_CHATGPT_API_ENDPOINT'; // Replace with your ChatGPT API endpoint const apiKey = 'YOUR_API_KEY'; // Replace with your API key const requestBody = { text: text, model: 'gpt-3.5-turbo', // Adjust the model according to your ChatGPT setup max_tokens: 100 }; const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }; const response = await fetch(apiUrl, { method: 'POST', headers: headers, body: JSON.stringify(requestBody) }); return response; }注意事项:替换代码中的 YOUR_CHATGPT_API_ENDPOINT 和 YOUR_API_KEY,这些信息应该是你的 ChatGPT API 的端点和密钥。插件需要访问页面内容的权限,因此在 manifest.json 中设置了 activeTab 权限。这个示例仅展示了基本的选择文本并获取回答的功能,实际应用中可能需要更多的错误处理和用户体验优化。
通过以上步骤,你可以创建一个 Chrome 插件,使用户能够在选择网页文本后,通过 ChatGPT 提供的 AI 回答功能获取问题的答案。
网友回复