-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
16 changed files
with
2,511 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,156 @@ | ||
--- | ||
title: 6、调用翻译 API | ||
urlname: csxtdf0gdbfudqg7 | ||
date: '2024-06-15 21:22:57' | ||
updated: '2024-06-15 21:23:18' | ||
description: 在这一章中,我们将学习如何选择合适的翻译 API,并且设置 API 访问权限,使用内容脚本调用翻译 API 并显示结果。这个章节将重点讲解如何在 Chrome 插件中实现在线翻译功能。6.1 选择合适的翻译 API6.1.1 Google Translate APIGoogle Transla... | ||
--- | ||
在这一章中,我们将学习如何选择合适的翻译 API,并且设置 API 访问权限,使用内容脚本调用翻译 API 并显示结果。这个章节将重点讲解如何在 Chrome 插件中实现在线翻译功能。 | ||
|
||
## 6.1 选择合适的翻译 API | ||
### 6.1.1 Google Translate API | ||
|
||
Google Translate API 是一个常用的翻译 API,支持多种语言。它的主要优点是准确性高,覆盖语言广泛。但是,这个 API 是收费的,需要先创建一个 Google Cloud 项目,并启用翻译 API。 | ||
|
||
### 6.1.2 免费翻译 API | ||
|
||
还有一些免费的翻译 API,比如: | ||
|
||
- LibreTranslate | ||
- MyMemory Translation API | ||
- Yandex.Translate API | ||
|
||
我们可以根据自己项目的需求和预算选择合适的翻译 API。 | ||
|
||
## 6.2 设置 API 访问权限 | ||
|
||
### 6.2.1 获取 API Key | ||
|
||
以 Google Translate API 为例,首先我们需要获取 API Key: | ||
|
||
1. 访问 [Google Cloud Console](https://console.cloud.google.com/) | ||
2. 创建一个新的项目或者使用已有项目。 | ||
3. 导航到“API 和服务” -> “启用 API 和服务”,搜索并启用“Cloud Translation API”。 | ||
4. 在“凭据”标签下,点击“创建凭据” -> “API 密钥”。 | ||
5. 复制生成的 API Key。 | ||
|
||
### 6.2.2 配置 API Key | ||
|
||
将获取的 API Key 保存到项目中: | ||
|
||
```json | ||
{ | ||
"apiKey": "YOUR_API_KEY" | ||
} | ||
``` | ||
|
||
将以上 JSON 文件保存为 `config.json`。 | ||
|
||
## 6.3 使用内容脚本调用翻译 API | ||
|
||
### 6.3.1 创建翻译函数 | ||
|
||
在 `content.js` 中,编写一个函数来调用翻译 API。以下是调用 Google Translate API 的示例代码: | ||
|
||
```javascript | ||
async function translateText(text, targetLanguage) { | ||
const apiKey = "YOUR_API_KEY"; | ||
const url = `https://translation.googleapis.com/language/translate/v2?key=${apiKey}`; | ||
const response = await fetch(url, { | ||
method: "POST", | ||
body: JSON.stringify({ | ||
q: text, | ||
target: targetLanguage, | ||
format: "text", | ||
}), | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
}); | ||
const data = await response.json(); | ||
if (data && data.data && data.data.translations) { | ||
return data.data.translations[0].translatedText; | ||
} else { | ||
throw new Error("Translation API error"); | ||
} | ||
} | ||
``` | ||
|
||
### 6.3.2 调用翻译函数 | ||
|
||
在 `content.js` 中,监听用户的选择操作,并调用翻译函数: | ||
|
||
```javascript | ||
document.addEventListener("mouseup", async () => { | ||
const selectedText = window.getSelection().toString().trim(); | ||
if (selectedText.length > 0) { | ||
try { | ||
const translatedText = await translateText(selectedText, "en"); | ||
console.log(`Translated Text: ${translatedText}`); | ||
// 这里可以进一步处理翻译结果,比如显示在界面上 | ||
} catch (error) { | ||
console.error(`Translation Error: ${error.message}`); | ||
} | ||
} | ||
}); | ||
``` | ||
|
||
## 6.4 显示翻译结果 | ||
|
||
为了在页面上显示翻译结果,我们可以创建一个简单的提示框: | ||
|
||
### 6.4.1 创建提示框样式 | ||
|
||
在 `content.css` 中添加提示框样式: | ||
|
||
```css | ||
#translate-popup { | ||
position: absolute; | ||
background: white; | ||
border: 1px solid #ccc; | ||
padding: 10px; | ||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); | ||
z-index: 1000; | ||
} | ||
``` | ||
|
||
### 6.4.2 在页面上显示提示框 | ||
|
||
在 `content.js` 中编写显示提示框的代码: | ||
|
||
```javascript | ||
function showPopup(text, x, y) { | ||
let popup = document.getElementById("translate-popup"); | ||
if (!popup) { | ||
popup = document.createElement("div"); | ||
popup.id = "translate-popup"; | ||
document.body.appendChild(popup); | ||
} | ||
popup.textContent = text; | ||
popup.style.left = `${x}px`; | ||
popup.style.top = `${y}px`; | ||
popup.style.display = "block"; | ||
} | ||
|
||
document.addEventListener("mouseup", async (event) => { | ||
const selectedText = window.getSelection().toString().trim(); | ||
if (selectedText.length > 0) { | ||
try { | ||
const translatedText = await translateText(selectedText, "en"); | ||
showPopup(translatedText, event.pageX, event.pageY); | ||
} catch (error) { | ||
console.error(`Translation Error: ${error.message}`); | ||
} | ||
} | ||
}); | ||
|
||
document.addEventListener("mousedown", () => { | ||
const popup = document.getElementById("translate-popup"); | ||
if (popup) { | ||
popup.style.display = "none"; | ||
} | ||
}); | ||
``` | ||
|
||
通过上述步骤,我们实现了调用翻译 API 并在页面上显示翻译结果的功能。 | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
--- | ||
title: 10、性能优化 | ||
urlname: dd58xbizumpbgilb | ||
date: '2024-06-15 21:24:32' | ||
updated: '2024-06-15 21:26:23' | ||
description: 在完成了插件的核心功能之后,插件的性能优化是确保用户获得最佳体验的关键一步。性能优化不仅能提升插件的加载速度,还能减少内存占用,优化 API 调用。通过这一章的学习,读者将掌握如何针对 Chrome 插件进行一系列性能优化操作。提升插件加载速度优化文件加载在开发 Chrome 插件时,合理组织... | ||
--- | ||
在完成了插件的核心功能之后,插件的性能优化是确保用户获得最佳体验的关键一步。性能优化不仅能提升插件的加载速度,还能减少内存占用,优化 API 调用。通过这一章的学习,读者将掌握如何针对 Chrome 插件进行一系列性能优化操作。 | ||
|
||
## 提升插件加载速度 | ||
|
||
### 优化文件加载 | ||
|
||
在开发 Chrome 插件时,合理组织和压缩文件可以显著提升插件的加载速度。 | ||
|
||
1. **压缩 JavaScript 和 CSS 文件**: | ||
使用工具如 UglifyJS 和 CSSNano 来压缩 JavaScript 和 CSS 文件,减少文件大小。 | ||
```bash | ||
# 安装 UglifyJS | ||
npm install -g uglify-js | ||
|
||
# 压缩 JavaScript 文件 | ||
uglifyjs popup.js -o popup.min.js | ||
|
||
# 安装 CSSNano | ||
npm install cssnano-cli -g | ||
|
||
# 压缩 CSS 文件 | ||
cssnano popup.css popup.min.css | ||
``` | ||
|
||
|
||
2. **延迟加载非关键资源**: | ||
仅在需要时加载非关键资源,例如某些图片、字体或额外的脚本。可以使用异步加载技术来实现。 | ||
```html | ||
<!-- 延迟加载 --> | ||
<script src="non-critical-script.js" defer></script> | ||
``` | ||
|
||
|
||
### 使用缓存 | ||
|
||
利用缓存机制存储不常变动的数据,可减少插件启动时的网络请求。 | ||
|
||
```javascript | ||
// 使用 Chrome Storage API 存储数据 | ||
chrome.storage.local.set({ cachedData: data }); | ||
|
||
// 加载时检查缓存 | ||
chrome.storage.local.get("cachedData", function (result) { | ||
if (result.cachedData) { | ||
// 使用缓存数据 | ||
processData(result.cachedData); | ||
} else { | ||
// 进行网络请求获取数据 | ||
fetchDataAndCache(); | ||
} | ||
}); | ||
``` | ||
|
||
## 减少内存占用 | ||
|
||
### 清理未使用的变量和事件监听器 | ||
|
||
在 JavaScript 中,未及时清理的变量和事件监听器可能会造成内存泄漏。确保在不再需要时清理它们。 | ||
|
||
```javascript | ||
function addEventListener() { | ||
const element = document.getElementById("button"); | ||
const handleClick = () => { | ||
// 事件处理逻辑 | ||
}; | ||
|
||
element.addEventListener("click", handleClick); | ||
|
||
// 在不再需要时移除事件监听 | ||
element.removeEventListener("click", handleClick); | ||
} | ||
``` | ||
|
||
### 使用合适的数据结构 | ||
|
||
根据实际需求选择合适的数据结构,例如数组、对象、Set 或 Map,以优化内存使用。 | ||
|
||
```javascript | ||
// 示例:使用 Set 而非数组来存储唯一值 | ||
const uniqueValues = new Set(); | ||
uniqueValues.add("value1"); | ||
uniqueValues.add("value2"); | ||
|
||
// 检查是否包含某个值 | ||
if (uniqueValues.has("value1")) { | ||
// 处理逻辑 | ||
} | ||
``` | ||
|
||
## 优化 API 调用 | ||
|
||
### 减少不必要的 API 调用 | ||
|
||
在调用 API 之前,检查是否有本地缓存的数据可以使用,避免重复请求。 | ||
|
||
```javascript | ||
function fetchTranslation(text) { | ||
const cacheKey = `translation_${text}`; | ||
|
||
chrome.storage.local.get(cacheKey, function (result) { | ||
if (result[cacheKey]) { | ||
// 使用缓存的翻译结果 | ||
displayTranslation(result[cacheKey]); | ||
} else { | ||
// 调用翻译 API 并缓存结果 | ||
callTranslationAPI(text).then((translation) => { | ||
chrome.storage.local.set({ [cacheKey]: translation }); | ||
displayTranslation(translation); | ||
}); | ||
} | ||
}); | ||
} | ||
``` | ||
|
||
### 使用批量请求 | ||
|
||
如果需要请求大量数据,尽量使用批量请求来减少网络开销。 | ||
|
||
```javascript | ||
// 示例:批量请求翻译结果 | ||
function fetchBatchTranslations(texts) { | ||
const endpoint = "https://api.example.com/batchTranslate"; | ||
fetch(endpoint, { | ||
method: "POST", | ||
body: JSON.stringify({ texts }), | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
}) | ||
.then((response) => response.json()) | ||
.then((data) => { | ||
// 处理批量翻译结果 | ||
processBatchTranslations(data); | ||
}); | ||
} | ||
``` | ||
|
||
通过上述性能优化方法,可以显著提升插件的加载速度,减少内存占用,并优化 API 调用,从而为用户提供更流畅的体验。性能优化不仅仅是技术细节的调整,更是提升用户满意度的重要手段。 | ||
|
Oops, something went wrong.