您好,登录后才能下订单哦!
随着全球化的发展,跨语言交流变得越来越普遍。无论是学习、工作还是娱乐,我们经常需要阅读和理解不同语言的文本。为了提升用户体验,许多浏览器扩展和工具提供了划词翻译功能,允许用户选中文本后立即获得翻译结果。本文将介绍如何使用JavaScript和ChatGPT API实现一个简单的划词翻译浏览器扩展。
ChatGPT API是由Open提供的一种自然语言处理接口,可以用于生成文本、翻译、问答等多种任务。通过调用ChatGPT API,我们可以实现高质量的文本翻译功能。
要使用ChatGPT API,首先需要注册Open账户并获取API密钥。API密钥是访问API的凭证,确保在代码中妥善保管。
为了开发浏览器扩展,我们需要一个基本的开发环境。可以使用任何文本编辑器(如VS Code)和现代浏览器(如Chrome或Firefox)进行开发。
首先,创建一个新的文件夹作为项目的根目录。在根目录下创建以下文件和文件夹:
/划词翻译扩展
│
├── manifest.json
├── background.js
├── content.js
├── popup.html
├── popup.js
└── styles.css
manifest.json
是浏览器扩展的配置文件,定义了扩展的基本信息和权限。
{
"manifest_version": 3,
"name": "划词翻译",
"version": "1.0",
"description": "使用ChatGPT API实现划词翻译的浏览器扩展",
"permissions": [
"activeTab",
"contextMenus",
"storage"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
background.js
是扩展的后台脚本,负责处理全局事件和API调用。
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "translate",
title: "翻译选中文本",
contexts: ["selection"]
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "translate") {
chrome.tabs.sendMessage(tab.id, { action: "translate", text: info.selectionText });
}
});
content.js
是内容脚本,运行在网页的上下文中,负责处理用户选中的文本并显示翻译结果。
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "translate") {
translateText(request.text).then(translation => {
showTranslation(translation);
});
}
});
function translateText(text) {
return fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer YOUR_API_KEY`
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "你是一个翻译助手,将用户输入的文本翻译成中文。" },
{ role: "user", content: text }
]
})
})
.then(response => response.json())
.then(data => {
return data.choices[0].message.content;
});
}
function showTranslation(translation) {
const translationDiv = document.createElement("div");
translationDiv.style.position = "fixed";
translationDiv.style.bottom = "20px";
translationDiv.style.right = "20px";
translationDiv.style.backgroundColor = "white";
translationDiv.style.border = "1px solid #ccc";
translationDiv.style.padding = "10px";
translationDiv.style.zIndex = "1000";
translationDiv.innerText = translation;
document.body.appendChild(translationDiv);
setTimeout(() => {
document.body.removeChild(translationDiv);
}, 5000);
}
popup.html
是扩展的弹出窗口,用户可以通过点击扩展图标打开它。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>划词翻译设置</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>划词翻译设置</h1>
<label for="apiKey">API密钥:</label>
<input type="text" id="apiKey" placeholder="输入你的API密钥">
<button id="save">保存</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
处理弹出窗口中的用户交互,例如保存API密钥。
document.getElementById("save").addEventListener("click", () => {
const apiKey = document.getElementById("apiKey").value;
chrome.storage.sync.set({ apiKey }, () => {
alert("API密钥已保存");
});
});
chrome.storage.sync.get("apiKey", (data) => {
if (data.apiKey) {
document.getElementById("apiKey").value = data.apiKey;
}
});
styles.css
用于美化弹出窗口。
body {
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
font-size: 20px;
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 10px;
}
input {
width: 100%;
padding: 8px;
margin-bottom: 20px;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
chrome://extensions/
。如果功能不正常,可以使用Chrome的开发者工具(F12)查看控制台输出,排查错误。
chrome://extensions/
页面,点击“打包扩展程序”。.crx
文件和.pem
私钥文件。通过本文的介绍,我们使用JavaScript和ChatGPT API实现了一个简单的划词翻译浏览器扩展。这个扩展可以帮助用户快速翻译网页中的选中文本,提升跨语言阅读的体验。未来,我们可以进一步优化扩展的功能,例如支持更多语言、自定义翻译样式等。
以上是一个基于JavaScript和ChatGPT API实现划词翻译浏览器扩展的详细教程。通过这个项目,你可以学习到如何开发浏览器扩展、调用API、处理用户交互等技能。希望这篇文章对你有所帮助,祝你开发顺利!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。