-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
260 lines (223 loc) · 8.17 KB
/
Copy pathbackground.js
File metadata and controls
260 lines (223 loc) · 8.17 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
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/**
* HoverPick — Background Service Worker
*
* Responsibilities:
* - Toggle picker mode state on icon click
* - Capture screen under the lens
* - Safe message routing to content scripts with lastError handling
* - Handle tab visibility, activation, and navigation events
*/
// ── State ──
let pickerActive = false;
let activeTabId = null;
// ═══════════════════════════════════════════════════════════════
// SAFE MESSAGE PASSING HELPER
// ═══════════════════════════════════════════════════════════════
/**
* Sends a message to a tab's content script.
* Uses a callback to intercept and clear chrome.runtime.lastError,
* preventing console warnings/errors when the content script is not yet ready.
*/
function sendMessageToTab(tabId, message) {
return new Promise((resolve) => {
chrome.tabs.sendMessage(tabId, message, (response) => {
const err = chrome.runtime.lastError;
if (err) {
resolve({ success: false, error: err.message });
} else {
resolve({ success: true, response });
}
});
});
}
// ═══════════════════════════════════════════════════════════════
// SCREEN CAPTURE
// ═══════════════════════════════════════════════════════════════
/**
* Capture the visible tab, hide overlay, and update offscreen frame.
*/
async function refreshCapture(tabId) {
if (!pickerActive || activeTabId !== tabId) return;
try {
// 1. Tell content script to hide overlay for capture
await sendMessageToTab(tabId, { type: 'PRE_CAPTURE' });
// 2. Capture the visible tab
const dataUrl = await chrome.tabs.captureVisibleTab(null, { format: 'png' });
// 3. Send to content script for local caching and sampling
await sendMessageToTab(tabId, {
type: 'NEW_FRAME',
dataUrl: dataUrl
});
// 4. Tell content script to restore overlay
await sendMessageToTab(tabId, { type: 'POST_CAPTURE' });
} catch (err) {
console.warn('[HoverPick:BG] Capture failed:', err);
// Ensure we restore the overlay even on error
await sendMessageToTab(tabId, { type: 'POST_CAPTURE' });
}
}
// ═══════════════════════════════════════════════════════════════
// ACTIVATION / DEACTIVATION
// ═══════════════════════════════════════════════════════════════
async function activatePicker(tab) {
if (pickerActive) return;
pickerActive = true;
activeTabId = tab.id;
// 1. Notify content script to activate (with lens initially hidden)
const result = await sendMessageToTab(tab.id, {
type: 'TOGGLE_PICKER',
active: true,
hiddenInitial: true
});
if (!result.success) {
// Content script not ready — inject manually, then retry
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
// Small delay to allow content script listener registration
await new Promise(resolve => setTimeout(resolve, 50));
const retryResult = await sendMessageToTab(tab.id, {
type: 'TOGGLE_PICKER',
active: true,
hiddenInitial: true
});
if (!retryResult.success) {
console.warn('[HoverPick:BG] Failed to activate content script after manual injection.');
deactivatePicker(tab.id);
return;
}
} catch (injectErr) {
console.warn('[HoverPick:BG] Script injection failed:', injectErr);
deactivatePicker(tab.id);
return;
}
}
// 2. Trigger initial capture
await refreshCapture(tab.id);
console.log('[HoverPick:BG] Picker activated');
}
async function deactivatePicker(tabId) {
if (!pickerActive) return;
pickerActive = false;
// Notify content script (fire and forget, safely)
if (tabId) {
sendMessageToTab(tabId, {
type: 'TOGGLE_PICKER',
active: false
});
}
activeTabId = null;
console.log('[HoverPick:BG] Picker deactivated');
}
// ═══════════════════════════════════════════════════════════════
// EVENT HANDLERS
// ═══════════════════════════════════════════════════════════════
// ── Icon Click: Binary ON/OFF Toggle ──
chrome.action.onClicked.addListener(async (tab) => {
// Guard: only http/https pages
if (!tab.url || (!tab.url.startsWith('http://') && !tab.url.startsWith('https://'))) {
return;
}
if (pickerActive) {
await deactivatePicker(tab.id);
} else {
await activatePicker(tab);
}
});
// ── Messages from Popup and Content Script ──
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
const fromContentScript = sender.tab != null;
// Popup says to start picker
if (message.type === 'START_PICKER') {
if (message.tab && !pickerActive) {
activatePicker(message.tab);
}
return false;
}
// Content script says user hit ESC or clicked
if (message.type === 'PICKER_DEACTIVATED' && fromContentScript) {
deactivatePicker(sender.tab.id);
return false;
}
// Content script requests screen capture refresh
if (message.type === 'REFRESH_CAPTURE' && fromContentScript) {
if (pickerActive && sender.tab.id === activeTabId) {
refreshCapture(sender.tab.id);
}
return false;
}
return false;
});
// ── Cleanup on tab close ──
chrome.tabs.onRemoved.addListener((tabId) => {
if (tabId === activeTabId) {
deactivatePicker(null);
}
});
// ── Cleanup on tab navigation ──
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (tabId === activeTabId && changeInfo.status === 'loading') {
deactivatePicker(tabId);
}
});
// ── Cleanup on active tab switch ──
chrome.tabs.onActivated.addListener((activeInfo) => {
if (pickerActive && activeInfo.tabId !== activeTabId) {
deactivatePicker(activeTabId);
}
});
// ── Context Menu: Format Settings (right-click icon) ──
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'format-hex',
title: 'Copy as HEX',
type: 'radio',
checked: true,
contexts: ['action']
});
chrome.contextMenus.create({
id: 'format-rgb',
title: 'Copy as RGB',
type: 'radio',
checked: false,
contexts: ['action']
});
console.log('[HoverPick:BG] Context menu created');
});
chrome.contextMenus.onClicked.addListener((info) => {
if (info.menuItemId === 'format-hex') {
chrome.storage.local.set({ colorFormat: 'HEX' });
} else if (info.menuItemId === 'format-rgb') {
chrome.storage.local.set({ colorFormat: 'RGB' });
}
});
// ── Command Keyboard Shortcut (Alt+C) ──
chrome.commands.onCommand.addListener(async (command) => {
if (command === 'activate-picker') {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab && tab.url) {
const isRestrictedPrefix = (url) => {
const restricted = [
'chrome://',
'chrome-extension://',
'view-source:',
'about:',
'https://chrome.google.com/webstore',
'https://chromewebstore.google.com',
'edge://'
];
return restricted.some(p => url.startsWith(p));
};
if (!isRestrictedPrefix(tab.url)) {
if (pickerActive) {
await deactivatePicker(tab.id);
} else {
await activatePicker(tab);
}
}
}
}
});
console.log('[HoverPick:BG] Background service worker initialized');