-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
80 lines (74 loc) · 2.16 KB
/
Copy pathbackground.js
File metadata and controls
80 lines (74 loc) · 2.16 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
/**
* ChatGPT Web Accelerator - Background Service Worker
*
* Dynamically enables/disables the action button and popup depending on the URL
* of the tab, ensuring it only triggers and is clickable on target ChatGPT pages.
*/
const TARGET_DOMAINS = [
'chatgpt.com',
'chat.openai.com'
];
/**
* Checks if the URL matches target domains.
* @param {string} urlStr
* @returns {boolean}
*/
function isTargetUrl(urlStr) {
if (!urlStr) return false;
try {
const url = new URL(urlStr);
// Check if hostname matches exactly or ends with target domain
return TARGET_DOMAINS.some(domain =>
url.hostname === domain || url.hostname.endsWith('.' + domain)
);
} catch (e) {
return false;
}
}
/**
* Updates the action and popup configuration for a specific tab.
* @param {number} tabId
* @param {string} url
*/
function updateTabAction(tabId, url) {
if (isTargetUrl(url)) {
chrome.action.enable(tabId, () => {
// Ignore errors if the tab was closed in the meantime
if (chrome.runtime.lastError) return;
chrome.action.setPopup({ tabId: tabId, popup: 'popup.html' });
});
} else {
chrome.action.disable(tabId, () => {
// Ignore errors if the tab was closed in the meantime
if (chrome.runtime.lastError) return;
chrome.action.setPopup({ tabId: tabId, popup: '' });
});
}
}
// 1. Listen for tab updates (e.g. navigation, URL changes)
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// If the tab contains a URL, check and update
if (tab && tab.url) {
updateTabAction(tabId, tab.url);
}
});
// 2. Listen for tab activation (e.g. switching tabs)
chrome.tabs.onActivated.addListener((activeInfo) => {
chrome.tabs.get(activeInfo.tabId, (tab) => {
if (chrome.runtime.lastError) return;
if (tab && tab.url) {
updateTabAction(activeInfo.tabId, tab.url);
}
});
});
// 3. Initialize all existing tabs on startup/install
chrome.runtime.onInstalled.addListener(() => {
chrome.tabs.query({}, (tabs) => {
if (chrome.runtime.lastError) return;
tabs.forEach((tab) => {
if (tab.id && tab.url) {
updateTabAction(tab.id, tab.url);
}
});
});
});