# crx-vue-vite **Repository Path**: Zroc/crx-vue-vite ## Basic Information - **Project Name**: crx-vue-vite - **Description**: 谷歌浏览器插件开发,content加载web components。 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-07-24 - **Last Updated**: 2025-08-21 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Vue 3 + TypeScript + Vite ## 初始化项目结构 ```shell . ├── src │ ├── assets │ │ └── vue.svg │ ├── background │ │ └── service-worker.ts │ ├── content │ │ └── content.ts │ ├── contentPage │ │ └── App.vue │ │ └── index.html │ │ └── main.ts │ │ └── style.css │ ├── customElement │ │ └── index.ts │ │ └── customElement.ce.vue │ ├── icons │ │ └── icon.png │ ├── popup │ │ └── App.vue │ │ └── index.html │ │ └── main.ts │ │ └── style.css │ └── vite-env.d.ts ├── .gitignore ├── manifest.json ├── package.json ├── README.md ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.node.json └── vite.config.ts ``` ## 参考材料 - [两万七千字大章带你使用 Vue3、Vite、TypeScript、Less、Pinia、Naive-ui 开发 Chrome V3 插件](https://juejin.cn/post/7327686547809337378#heading-0) - [基于 Vite4+Vue3 的 Chrome 插件开发教程](https://juejin.cn/post/7269357836026298425) - [Vue 进阶-自定义元素 API](https://cn.vuejs.org/api/custom-elements.html#definecustomelement) - [谷歌插件开发小册](https://gitee.com/linwu-hi/coding-time-chrome#%E7%9B%AE%E5%BD%95) ## 进阶学习 #### 插件生命周期 - 安装或更新 ```js // 在background脚本chrome.runtime.onInstalled chrome.runtime.onInstalled.addListener(function (details) { if (details.reason == "install") { console.log("This is a first install!"); } else if (details.reason == "update") { console.log( "Updated from " + details.previousVersion + " to " + chrome.runtime.getManifest().version + "!" ); } }); ``` - 启动:用户打开浏览器时,插件会被启动。插件可以在这个阶段初始化数据,设置默认状态等。 ```js chrome.runtime.onStartup.addListener(function () { console.log("Browser started, initialize plugin data."); }); ``` - 运行:插件被启动后,就进入了运行阶段。在这个阶段,插件可以响应用户操作,监听和处理浏览器事件,提供各种功能。 ```js chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { if (changeInfo.status == "complete" && tab.active) { console.log("Active tab updated, let's do something!"); } }); ``` - 停止:用户关闭浏览器时,插件会被停止。插件可以监听 chrome.runtime.onSuspend 事件,保存数据,清理资源等。 ```js chrome.runtime.onSuspend.addListener(function () { console.log("Browser is about to close, save plugin data."); }); ``` - 卸载:用户从浏览器中卸载插件时,插件的生命周期就结束了。插件可以监听 chrome.runtime.onInstalled 事件的 uninstall 原因,执行卸载操作。 ```js chrome.runtime.setUninstallURL( "https://your_website.com/uninstall", function () { console.log("Uninstall URL has been set"); } ); ``` #### 插件事件系统 - 浏览器启动事件: 你可以通过监听 chrome.runtime.onStartup 事件来知道浏览器启动。 ```js chrome.runtime.onStartup.addListener(function () { console.log("Browser has been started."); }); ``` - 浏览器关闭事件: Chrome 没有提供浏览器关闭的直接事件,但是可以使用 chrome.windows.onRemoved 事件在最后一个浏览器窗口关闭时执行操作。 ```js chrome.windows.onRemoved.addListener(function (windowId) { chrome.windows.getAll({}, function (windows) { if (windows.length == 0) { console.log("Browser is closing, the last window was closed."); } }); }); ``` - 打开新窗口事件: 你可以通过监听 chrome.windows.onCreated 事件来知道新窗口打开。 ```js chrome.windows.onCreated.addListener(function () { console.log("New window opened."); }); ``` - 关闭窗口事件: 你可以通过监听 chrome.windows.onRemoved 事件来知道窗口关闭。 ```js chrome.windows.onRemoved.addListener(function (windowId) { console.log("Window with id " + windowId + " was closed."); }); ``` - 切换标签页事件: 你可以通过监听 chrome.tabs.onActivated 事件来知道标签页切换。 ```js chrome.tabs.onActivated.addListener(function (activeInfo) { console.log("Tab with id " + activeInfo.tabId + " is now active."); }); ``` - 监听网络请求 - 请求发送事件: 你可以通过监听 chrome.webRequest.onBeforeRequest 事件来知道请求发送。 ```js chrome.webRequest.onBeforeRequest.addListener( function (details) { console.log("Request is about to be sent: ", details); }, { urls: [""] } ); ``` - 响应接收事件: 你可以通过监听 chrome.webRequest.onCompleted 事件来知道响应接收。 ```js chrome.webRequest.onCompleted.addListener( function (details) { console.log("Request completed: ", details); }, { urls: [""] } ); ``` - 连接错误事件: 你可以通过监听 chrome.webRequest.onErrorOccurred 事件来知道连接错误。 ```js chrome.webRequest.onErrorOccurred.addListener( function (details) { console.log("Error occurred while making request: ", details); }, { urls: [""] } ); ``` - 点击插件图标事件: 你可以通过监听 chrome.browserAction.onClicked 事件来知道插件图标被点击。 ```js chrome.browserAction.onClicked.addListener(function (tab) { console.log("Plugin icon clicked in tab with id " + tab.id + "."); }); ``` - 选择插件菜单事件: 首先需要创建菜单,然后通过监听 chrome.contextMenus.onClicked 事件来知道插件菜单被选择。 ```js chrome.contextMenus.create({ id: "sampleContextMenu", title: "Sample Context Menu", contexts: ["page"], }); chrome.contextMenus.onClicked.addListener(function (info, tab) { if (info.menuItemId == "sampleContextMenu") { console.log("Sample Context Menu clicked."); } }); ``` - 使用快捷键事件: 快捷键需要在 manifest.json 文件中定义,然后通过监听 chrome.commands.onCommand 事件来知道快捷键被使用。 ```js cchrome.commands.onCommand.addListener(function (command) { console.log("User triggered command: " + command); }); ``` #### 插件权限系统与内容安全策略(CSP) 插件需要的权限需要在 manifest.json 文件中的 "permissions" 部分进行声明。例如,如果一个插件需要访问用户的浏览历史,那么它需要添加 "history" 权限: ```json { "name": "My extension", ... "permissions": [ "history" ], ... } ``` 内容安全策略(Content Security Policy,简称 CSP)是一种安全标准,用于预防跨站脚本攻击(XSS)和数据注入攻击。默认的 CSP 策略禁止扩展加载远程 JavaScript 或 CSS,只允许从扩展包内部加载。也就是说,你不能直接在你的 HTML 文件中引用一个外部的 JS 或 CSS 文件,所有的 JS 和 CSS 都应该以文件的形式包含在扩展包中。 ```json { "name": "My extension", ... "content_security_policy": "script-src 'self' https://example.com; object-src 'self'", ... } ``` #### 深入了解 Chrome API - 插件中的消息传递 在插件中,我们通常需要在不同的脚本之间进行通信,例如在 background 脚本和 content 脚本之间,或者在 popup 脚本和 background 脚本之间。Chrome 提供了 chrome.runtime.sendMessage 和 chrome.runtime.onMessageAPI,用于在插件的不同组件之间发送和接收消息。 以下是一个在 content 脚本中发送消息,并在 background 脚本中接收消息的示例: ```js // content script chrome.runtime.sendMessage({ greeting: "hello" }, function (response) { console.log(response.farewell); }); // background script chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { if (request.greeting == "hello") sendResponse({ farewell: "goodbye" }); }); ``` - 使用 tabs API chrome.tabs API 允许插件操作浏览器的标签页,例如创建新的标签页,关闭标签页,切换标签页,修改标签页的 URL 等。以下是一个创建新标签页的示例: ```js chrome.tabs.create({ url: "http://www.example.com" }); ``` - 使用 bookmarks API chrome.bookmarks API 允许插件操作用户的书签,例如创建书签,删除书签,搜索书签等。以下是一个创建书签的示例: ```js chrome.bookmarks.create({ parentId: "1", title: "Extension bookmarks", url: "http://www.example.com", }); ``` - 使用 notifications API chrome.notifications API 允许插件发送桌面通知。以下是一个发送通知的示例: ```js chrome.notifications.create({ type: "basic", iconUrl: "icon.png", title: "Notification title", message: "Notification message", }); ``` - 使用 webRequest API chrome.webRequest API 允许插件监控和修改网络请求。例如,以下代码监听所有的网络请求,并在控制台中打印请求的 URL: ```js chrome.webRequest.onBeforeRequest.addListener( function (details) { console.log(details.url); }, { urls: [""] }, ["blocking"] ); ``` - 更多 API 除了上述提到的 API,Chrome 还提供了许多其他功能强大的 API,可以满足不同插件的需求。 - storage API 用于在插件中存储和读取数据。 ```js // 保存数据 chrome.storage.sync.set({ key: value }, function () { console.log("Data saved."); }); // 读取数据 chrome.storage.sync.get("key", function (result) { console.log("Data retrieved: ", result.key); }); ``` - alarms API 用于创建和管理定时任务。 ```js // 创建定时任务 chrome.alarms.create("alarmName", { delayInMinutes: 10 }); // 监听定时任务触发事件 chrome.alarms.onAlarm.addListener(function (alarm) { console.log("Alarm triggered: ", alarm); }); ``` - contextMenus API 用于在浏览器上下文菜单中添加自定义菜单项。 ```js // 创建上下文菜单 chrome.contextMenus.create({ id: "menuItemId", title: "Menu Item", contexts: ["page"], }); // 监听菜单项点击事件 chrome.contextMenus.onClicked.addListener(function (info, tab) { console.log("Menu item clicked: ", info.menuItemId); }); ``` 更多详见[谷歌插件 API](https://developer.chrome.com/docs/extensions/reference/) #### 插件开发实战示例 - 与网页内容进行交互 与网页内容进行交互是 Chrome 插件开发中常见的需求,可以通过内容脚本和消息传递来实现。下面是如何与网页内容进行交互的示例: ```js // Content script // 监听来自插件的消息 chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { if (message.action === "changeColor") { // 修改网页元素的颜色 document.body.style.backgroundColor = message.color; sendResponse({ message: "Color changed!" }); } }); // 向插件发送消息 chrome.runtime.sendMessage({ action: "getData" }, function (response) { console.log("Data received from plugin: ", response.data); }); // Background script // 向内容脚本发送消息 chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { chrome.tabs.sendMessage( tabs[0].id, { action: "changeColor", color: "#FF0000" }, function (response) { console.log("Response from content script: ", response.message); } ); }); // 监听来自内容脚本的消息 chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { if (message.action === "getData") { // 获取数据并发送给内容脚本 sendResponse({ data: "Some data from plugin" }); } }); ``` - 保存用户设置和数据 插件可以使用 Chrome 的存储 API(storage API)来保存用户设置和数据。下面是使用 storage API 保存和读取数据的示例: ```js // 保存数据 chrome.storage.sync.set({ key: value }, function () { console.log("Data saved."); }); // 读取数据 chrome.storage.sync.get("key", function (result) { console.log("Data retrieved: ", result.key); }); ``` - 实现插件的国际化 插件的国际化是为了让插件能够支持多语言环境,并提供不同语言的翻译。以下是如何实现插件的国际化的示例: 在插件的根目录下创建一个名为 \_locales 的文件夹。 在 \_locales 文件夹中创建一个子文件夹,以语言代码命名(例如 en 表示英语,zh_CN 表示简体中文)。 在每个语言代码的文件夹中,创建一个 messages.json 文件,用于存储对应语言的翻译。 例如,在 en 文件夹中的 messages.json 可以包含如下内容: ```json { "pluginTitle": { "message": "My Plugin" }, "greeting": { "message": "Hello, world!" } } ``` 在插件的代码中使用 `chrome.i18n.getMessage` 方法来获取对应语言的翻译。 ```js // 获取插件标题的翻译 var pluginTitle = chrome.i18n.getMessage("pluginTitle"); // 获取问候语的翻译 var greeting = chrome.i18n.getMessage("greeting"); ``` 如果当前语言环境没有对应的翻译,将会使用默认的翻译(默认翻译可以在 messages.json 中指定)。 通过以上步骤,插件可以根据用户的语言设置自动加载对应的翻译文件,实现国际化功能。 请注意,在 manifest.json 文件中的 "default_locale" 字段中指定插件的默认语言。 ```json { "name": "My Plugin", ... "default_locale": "en", ... } ``` #### 插件测试与调试 - Chrome 插件的调试技巧 1. 使用 console.log()打印调试信息:在开发过程中,可以使用 console.log()在开发者工具的控制台中输出信息,以便查看变量的值、代码的执行流程等。 2. 使用 debugger 关键字设置断点:在代码中插入 debugger 关键字可以在开发者工具中设置断点,当代码执行到此处时会暂停执行,以便进行逐行调试。 3. 使用 chrome.runtime.onInstalled 事件:可以在插件安装或更新时,监听 chrome.runtime.onInstalled 事件来执行一些调试任务,如初始化数据、显示调试信息等。 4. 使用 Chrome 开发者工具:Chrome 提供了强大的开发者工具,包括元素检查、网络监控、性能分析等功能,可以帮助调试和优化插件的开发过程。 ```js console.log("Variable value:", variable); function myFunction() { // ... debugger; // ... } chrome.runtime.onInstalled.addListener(function (details) { if (details.reason == "install") { console.log("Extension installed."); } else if (details.reason == "update") { console.log("Extension updated."); } }); ``` - 使用 automated testing 进行插件测试 自动化测试(automated testing)是一种在开发过程中自动执行测试用例的方法,可以提高测试效率并确保插件的功能和稳定性。 在 Chrome 插件开发中,可以使用一些测试框架和工具来进行自动化测试,例如: ```js // Jasmine:是一个流行的JavaScript测试框架,可以用于编写和执行单元测试、集成测试等。 describe("MyPlugin", function () { it("should do something", function () { expect(myPlugin.doSomething()).toBe(true); }); it("should handle async operations", function (done) { myPlugin.doAsyncOperation(function (result) { expect(result).toBe(true); done(); }); }); }); // Selenium WebDriver:是一个用于自动化浏览器操作的工具,可以模拟用户在浏览器中的交互行为,用于编写端到端(end-to-end)测试。 const { Builder, By, Key } = require("selenium-webdriver"); async function myTest() { let driver = await new Builder().forBrowser("chrome").build(); try { await driver.get("https://www.example.com"); await driver.findElement(By.name("q")).sendKeys("test", Key.ENTER); let title = await driver.getTitle(); console.log("Page title:", title); } finally { await driver.quit(); } } myTest(); ``` - 使用 DevTools 进行性能分析 Chrome 开发者工具提供了强大的性能分析功能,可以帮助开发者找出插件中的性能瓶颈和优化点。以下是使用 DevTools 进行性能分析的步骤: 1. 打开 Chrome 开发者工具(快捷键:F12)。 2. 切换到"Performance"选项卡。 3. 点击"Record"按钮开始录制性能数据。 4. 进行一些操作,以触发插件的功能。 5. 停止录制,分析性能数据。 在性能分析结果中,可以查看函数的执行时间、内存使用情况、页面加载时间等信息,以便找出性能瓶颈和进行优化。 性能分析可以帮助开发者优化插件的执行效率和资源占用,提高插件的性能和用户体验。 #### 插件发布与维护 - 在 Chrome Web Store 发布和更新插件 1. 登录到 Chrome 开发者控制台。 2. 创建一个新的开发者账号或使用现有的账号。 3. 在开发者控制台中,选择"开发者中心"并点击"新增项目"按钮。 4. 提供插件的基本信息,包括名称、描述、图标等。 5. 上传插件的压缩文件(.zip 格式),其中包含了插件的所有文件和资源。 6. 填写其他必要的信息,如分类、语言、隐私政策等。 7. 验证插件的所有权限,并确保插件符合 Chrome Web Store 的规定和政策。 8. 提交插件进行审核。审核过程可能需要几天时间。 9. 一旦插件审核通过,它将在 Chrome Web Store 上可见,用户可以进行安装。 10. 对于更新插件,可以通过上传新版本的压缩文件并更新插件的信息。 - 插件的版本管理与错误处理 在插件的开发和维护过程中,版本管理和错误处理是非常重要的。以下是一些常见的版本管理和错误处理技巧: ```js // 版本管理:对于插件的每个发布版本,应使用语义化版本号(Semantic Versioning)来管理。可以在插件的manifest.json文件中指定版本号,并确保每个版本的更新都有明确的变更记录。 { "manifest_version": 2, "version": "1.0.0", ... } // 错误处理:在插件中使用适当的错误处理机制可以提高插件的健壮性。可以使用try...catch语句来捕获并处理可能出现的错误,以及使用console.error()方法将错误信息输出到控制台。 try { // 代码块可能抛出错误的部分 } catch (error) { console.error("An error occurred:", error); } ``` - 插件的安全性和隐私保护 在插件开发过程中,确保插件的安全性和保护用户隐私是至关重要的。以下是一些常见的安全性和隐私保护措施: 1. 权限管理:在 manifest.json 文件中,只授予插件所需的最小权限。不要授予过多的权限,以避免滥用用户的隐私。 ```json { "manifest_version": 2, "permissions": [ "storage", "tabs" ], ... } ``` 2. 数据保护:在处理用户数据时,采取适当的安全措施,如数据加密、安全传输等,以防止数据泄露或被恶意使用。 3. 更新检查:定期检查插件的更新并及时应用,以修复安全漏洞和错误,并提供用户所需的新功能。 4. 安全审查:在开发过程中,进行安全审查,包括代码审查和漏洞扫描,以确保插件没有潜在的安全问题。 5. 隐私政策:如果插件收集用户个人信息,应提供清晰的隐私政策,并遵守相关的数据保护法律和规定。