-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackground.js
188 lines (168 loc) · 6.26 KB
/
background.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
// Create context menus
chrome.runtime.onInstalled.addListener(() => {
// 设置默认的 prompts
const defaultPrompts = [
"开局一个碗,结局一根绳。发挥你的想象力,撰写一段波澜壮阔的关于一个王朝兴衰的历史故事",
"Begin with a bowl and end with a rope. Unleash your imagination to craft an epic historical tale."
];
// 初始化存储
chrome.storage.local.get(['prompts'], (result) => {
if (!result.prompts) {
chrome.storage.local.set({ prompts: defaultPrompts });
}
});
// Initial setup of menus
createContextMenus();
});
// 创建防抖函数
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// 使用防抖包装 createContextMenus
const debouncedCreateContextMenus = debounce(createContextMenus, 100);
// 添加标签页激活监听器
chrome.tabs.onActivated.addListener(() => {
debouncedCreateContextMenus();
});
// 添加窗口焦点变化监听器
chrome.windows.onFocusChanged.addListener(() => {
debouncedCreateContextMenus();
});
// Handle context menu clicks
chrome.contextMenus.onClicked.addListener((info, tab) => {
try {
if (info.menuItemId === "savePrompt") {
const selectedText = info.selectionText;
chrome.storage.local.get(['prompts'], (result) => {
const prompts = result.prompts || [];
prompts.push(selectedText);
chrome.storage.local.set({ prompts }, () => {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon48.png',
title: 'Easy Prompt',
message: 'Text saved successfully!'
});
});
});
} else if (info.menuItemId.startsWith('insert_prompt_')) {
const index = parseInt(info.menuItemId.replace('insert_prompt_', ''));
chrome.storage.local.get(['prompts'], (result) => {
const prompts = result.prompts || [];
if (prompts[index]) {
// 检查是否可以访问该页面
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const currentTab = tabs[0];
if (currentTab && currentTab.url &&
!currentTab.url.startsWith('chrome://') &&
!currentTab.url.startsWith('chrome-extension://')) {
chrome.scripting.executeScript({
target: { tabId: currentTab.id },
func: (text) => {
const activeElement = document.activeElement;
if (activeElement && (activeElement.isContentEditable ||
activeElement.tagName === 'INPUT' ||
activeElement.tagName === 'TEXTAREA')) {
const start = activeElement.selectionStart || 0;
const end = activeElement.selectionEnd || 0;
if (activeElement.isContentEditable) {
// 处理可编辑内容
const selection = window.getSelection();
if (selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(text));
}
} else {
// 处理输入框
const currentValue = activeElement.value;
activeElement.value = currentValue.substring(0, start) +
text +
currentValue.substring(end);
// 更新光标位置
activeElement.selectionStart = activeElement.selectionEnd = start + text.length;
// 触发事件
activeElement.dispatchEvent(new Event('input', { bubbles: true }));
activeElement.dispatchEvent(new Event('change', { bubbles: true }));
}
}
},
args: [prompts[index]]
}).catch(error => {
console.error('Failed to execute script:', error);
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon48.png',
title: 'Easy Prompt',
message: 'Cannot insert text in this page'
});
});
}
});
}
});
}
} catch (error) {
console.error('Error in context menu click handler:', error);
}
});
// 只在存储变化时更新菜单
chrome.storage.onChanged.addListener((changes, namespace) => {
if (namespace === 'local' && changes.prompts) {
debouncedCreateContextMenus();
}
});
// Function to create context menus
async function createContextMenus() {
try {
// 确保移除所有现有菜单
await new Promise((resolve) => {
chrome.contextMenus.removeAll(() => {
resolve();
});
});
const result = await new Promise((resolve) => {
chrome.storage.local.get(['prompts'], resolve);
});
const prompts = result.prompts || [];
// 使用 Promise 包装 create 操作
const createMenu = (options) => new Promise((resolve) => {
chrome.contextMenus.create(options, resolve);
});
// Create save menu
await createMenu({
id: "savePrompt",
title: "Save to Easy Prompt",
contexts: ["selection"]
});
if (prompts.length > 0) {
// Create parent menu
await createMenu({
id: 'insertPromptParent',
title: 'Insert Prompt',
contexts: ['editable']
});
// Create submenu items sequentially
for (let i = 0; i < prompts.length; i++) {
const prompt = prompts[i];
const title = prompt.length > 30 ? prompt.substring(0, 27) + '...' : prompt;
await createMenu({
id: `insert_prompt_${i}`,
parentId: 'insertPromptParent',
title: title,
contexts: ['editable']
});
}
}
} catch (error) {
console.error('Error creating context menus:', error);
}
}