kimi ai 生成,测试可用,需要自行准备图标文件
创建一个简单的Chrome插件来实现选择文本后的搜索功能,你需要完成以下几个步骤:
-
创建插件的基础文件夹和文件:
- 创建一个文件夹用于存放插件的所有文件。
- 在该文件夹中创建以下文件:
manifest.json
:插件的配置文件。popup.html
:右键菜单选择后的弹出页面。popup.js
:弹出页面的JavaScript逻辑。background.js
:后台脚本,用于处理搜索逻辑。
-
配置
manifest.json
:{ "manifest_version": 3, "name": "Bing Search", "version": "1.0", "description": "Search selected text with Bing", "permissions": ["contextMenus"], "background": { "service_worker": "background.js" }, "action": { "default_popup": "popup.html", "default_icon": { "16": "images/icon16.png", "48": "images/icon48.png", "128": "images/icon128.png" } }, "icons": { "16": "images/icon16.png", "48": "images/icon48.png", "128": "images/icon128.png" } }
- 请确保你的插件文件夹中包含图标文件。
-
创建
popup.html
:<!DOCTYPE html> <html> <head> <title>Search with Bing</title> <script src="popup.js"></script> </head> <body> <h1>Search with Bing</h1> </body> </html>
-
编写
popup.js
:document.addEventListener('DOMContentLoaded', function() { document.body.addEventListener('click', function(event) { if (event.target.tagName === 'A') { chrome.runtime.sendMessage({searchQuery: window.getSelection().toString()}); } }); });
-
编写
background.js
: -
添加右键菜单项:
- 你需要在
background.js
中添加逻辑来创建上下文菜单项。
- 你需要在
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.searchQuery) {
const searchUrl = https://www.sogou.com/search?q=${encodeURIComponent(request.searchQuery)}
;
chrome.tabs.create({ url: searchUrl });
}
}
);
chrome.contextMenus.create({
id: “searchWithBing”,
title: “Search with Bing”,
contexts: [“selection”]
});
chrome.contextMenus.onClicked.addListener(function(info) {
if (info.menuItemId === “searchWithBing”) {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
var currentTabIndex = tabs[0].index;
const activeTab = tabs[0];
chrome.tabs.create({
url: https://www.bing.com/search?q=${encodeURIComponent(info.selectionText)}
, index: currentTabIndex + 1,
openerTabId: tabs[0].id // 使用当前标签页的 ID 作为 openerTabId
}, function(newTab) {
// 检查活动标签页是否已经在一个分组中
if (activeTab.groupId !== chrome.tabGroups.TAB_GROUP_ID_NONE) {
var groupId = activeTab.groupId;
// 使用 chrome.tabs.group 方法将新标签页加入到分组
chrome.tabs.group({ tabIds: newTab.id, groupId: groupId });
} else {
console.log("Active tab is not in a group.");
}
// 如果当前标签页在分组中,将新标签页也加入该分组
// if (activeTab.groupId !== -1) { // -1 表示标签页不在任何分组中
// chrome.tabs.update(newTab.id, {groupId: activeTab.groupId});
// }
// 将新标签页移动到当前标签页的旁边
chrome.tabs.move(newTab.id, {index: currentTabIndex + 1});
});
});
}
});
7. **加载插件到Chrome**:
- 打开Chrome,进入`chrome://extensions/`。
- 开启“开发者模式”。
- 点击“加载已解压的扩展程序”,选择你的插件文件夹。
8. **测试插件**:
- 在网页上选择文本,右键点击,应该看到“Search with Bing”选项。
- 选择该选项,应打开一个新的标签页并用Bing搜索所选文本。
请注意,上述代码仅为示例,实际开发中可能需要进一步的调整和完善。此外,由于Chrome插件API的更新,部分API可能有变动,请根据最新的Chrome插件开发文档进行适配。