-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
67 lines (58 loc) · 2.21 KB
/
background.js
File metadata and controls
67 lines (58 loc) · 2.21 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
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.set({ laserEnabled: false });
// Inject content script into all existing tabs
chrome.tabs.query({}, (tabs) => {
for (const tab of tabs) {
if (tab.id && tab.url && /^https?:/.test(tab.url)) {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
}).catch(err => console.warn('Script injection failed on tab', tab.id, err));
chrome.scripting.insertCSS({
target: { tabId: tab.id },
files: ['styles.css']
}).catch(err => console.warn('CSS injection failed on tab', tab.id, err));
}
}
});
});
// Handle messages from popup and inject content script if needed
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'ENSURE_CONTENT_SCRIPT') {
// Get the active tab
chrome.tabs.query({ active: true, currentWindow: true }, async (tabs) => {
if (tabs[0]) {
const tabId = tabs[0].id;
try {
// Try to ping the content script first
const response = await chrome.tabs.sendMessage(tabId, { type: 'PING' });
sendResponse({ contentScriptReady: true });
} catch (error) {
// Content script not ready, inject it
try {
await chrome.scripting.executeScript({
target: { tabId: tabId },
files: ['content.js']
});
// Also inject CSS
await chrome.scripting.insertCSS({
target: { tabId: tabId },
files: ['styles.css']
});
// Wait a bit for injection to complete
setTimeout(() => {
sendResponse({ contentScriptReady: true, injected: true });
}, 100);
} catch (injectionError) {
console.error('Failed to inject content script:', injectionError);
sendResponse({ contentScriptReady: false, error: injectionError.message });
}
}
}
});
return true; // Keep the message channel open for async response
}
});
chrome.runtime.onSuspend.addListener(() => {
// Optional: clean up if needed
});