-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
68 lines (59 loc) · 2.05 KB
/
Copy pathbackground.js
File metadata and controls
68 lines (59 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// GeoAddon - Background Service Worker (Manifest V3)
// V1: 划词右键菜单 -> Google Maps / Wikipedia 搜索
//
// 架构说明:
// - 所有逻辑集中在此 Service Worker 中,无 content script,零侵入网页。
// - 菜单项通过 SEARCH_PROVIDERS 注册表声明,未来新增搜索源(如 OSM、Bing、百度地图)
// 只需在数组里追加一项,无需改动事件处理逻辑。
const PARENT_MENU_ID = "geoaddon-parent";
/**
* 搜索源注册表。新增条目即可扩展子菜单。
* - id: chrome.contextMenus 的唯一 ID
* - title: 子菜单显示文案(含 emoji)
* - buildUrl: (selectionText) => 目标 URL
*/
const SEARCH_PROVIDERS = [
{
id: "geoaddon-google-maps",
title: "🗺️ Google Maps",
buildUrl: (query) =>
`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`,
},
{
id: "geoaddon-wikipedia",
title: "📖 Wikipedia",
buildUrl: (query) =>
`https://en.wikipedia.org/wiki/Special:Search?search=${encodeURIComponent(query)}`,
},
];
const PROVIDER_BY_ID = new Map(SEARCH_PROVIDERS.map((p) => [p.id, p]));
function createMenus() {
// 父菜单:%s 会被浏览器替换为当前选中的文本
chrome.contextMenus.create({
id: PARENT_MENU_ID,
title: "🌍 Geo 搜索: '%s'",
contexts: ["selection"],
});
for (const provider of SEARCH_PROVIDERS) {
chrome.contextMenus.create({
id: provider.id,
parentId: PARENT_MENU_ID,
title: provider.title,
contexts: ["selection"],
});
}
}
// Service Worker 可能被重复唤醒;先清空再创建可避免「重复 ID」错误。
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.removeAll(() => createMenus());
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
const provider = PROVIDER_BY_ID.get(info.menuItemId);
if (!provider) return;
const query = (info.selectionText || "").trim();
if (!query) return;
chrome.tabs.create({
url: provider.buildUrl(query),
index: tab ? tab.index + 1 : undefined,
});
});