-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
221 lines (196 loc) · 7.15 KB
/
background.js
File metadata and controls
221 lines (196 loc) · 7.15 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
const DEFAULT_SETTINGS = {
showWidget: false,
reloadPage: true,
closePopup: true,
protectedWeb: false,
clearCookies: true,
clearCache: true,
clearCacheStorage: true,
clearFileSystems: false,
clearIndexedDB: false,
clearLocalStorage: true,
clearSessionStorage: true,
clearServiceWorkers: false,
clearWebSQL: false,
settingsVisited: false,
lastSeenVersion: chrome.runtime.getManifest().version
};
/**
* Clears data for a specific tab based on settings.
* @param {chrome.tabs.Tab} tab - The tab to clear data for.
* @param {Object} [settings] - Optional settings override.
*/
async function clearData(tab, settings = null) {
if (!tab || !tab.url) {
console.error("Tab or URL unavailable");
return;
}
// Update badge to indicate processing
chrome.action.setBadgeText({ text: "🗑️", tabId: tab.id });
try {
// Validate URL
try {
new URL(tab.url);
} catch (e) {
throw new Error("Invalid URL provided");
}
// Get settings if not provided
if (!settings) {
settings = await chrome.storage.local.get([
"reloadPage", "clearCookies", "clearCache", "clearCacheStorage",
"clearFileSystems", "clearIndexedDB", "clearLocalStorage",
"clearSessionStorage", "clearServiceWorkers", "clearWebSQL",
"protectedWeb"
]);
}
const origins = [tab.url];
const originTypes = { unprotectedWeb: true };
if (settings.protectedWeb) {
originTypes.protectedWeb = true;
}
const removalOptions = {
cache: settings.clearCache,
cacheStorage: settings.clearCacheStorage,
cookies: settings.clearCookies,
fileSystems: settings.clearFileSystems,
indexedDB: settings.clearIndexedDB,
localStorage: settings.clearLocalStorage,
serviceWorkers: settings.clearServiceWorkers,
webSQL: settings.clearWebSQL
};
// 1. Clear via browsingData API
try {
await chrome.browsingData.remove({ originTypes, origins }, removalOptions);
} catch (e) {
console.error("Error clearing browsingData:", e);
throw e;
}
// 2. Clear via Content Script (for Storage APIs that might need context or are more reliable from within)
if (settings.clearLocalStorage || settings.clearSessionStorage || settings.clearIndexedDB) {
try {
await chrome.tabs.sendMessage(tab.id, {
action: "clearStorageData",
clearLocalStorage: settings.clearLocalStorage,
clearSessionStorage: settings.clearSessionStorage,
clearIndexedDB: settings.clearIndexedDB
});
} catch (e) {
console.log("Content script unavailable or error:", e);
}
}
// 3. Manual Cookie Cleanup (Fallback/Specific handling)
if (settings.clearCookies) {
try {
const cookies = await chrome.cookies.getAll({ url: tab.url });
for (const cookie of cookies) {
await removeCookie(cookie);
}
} catch (e) {
console.log("Additional cookie clearing error:", e);
}
}
// 4. Reload Page
if (settings.reloadPage) {
chrome.tabs.reload(tab.id);
}
// Success Badge
chrome.action.setBadgeText({ text: "✅", tabId: tab.id });
} catch (e) {
console.error("Error clearing data:", e);
chrome.action.setBadgeText({ text: "❌", tabId: tab.id });
} finally {
// Clear badge after delay
setTimeout(() => {
chrome.action.setBadgeText({ text: "", tabId: tab.id });
}, 2000);
}
}
/**
* Manually removes a cookie.
* @param {chrome.cookies.Cookie} cookie
*/
function removeCookie(cookie) {
return new Promise((resolve) => {
const protocols = cookie.secure ? ["https:"] : ["http:", "https:"];
let removed = false;
let completed = 0;
for (const protocol of protocols) {
const domain = cookie.domain.startsWith(".") ? cookie.domain.substring(1) : cookie.domain;
const url = `${protocol}//${domain}${cookie.path}`;
const details = {
url: url,
name: cookie.name,
storeId: cookie.storeId
};
if (cookie.partitionKey) {
details.partitionKey = cookie.partitionKey;
}
chrome.cookies.remove(details, (details) => {
completed++;
if (details) removed = true;
if (completed === protocols.length) {
resolve(removed);
}
});
}
});
}
// Event Listeners
chrome.action.onClicked.addListener(async (tab) => {
// This might not trigger if a popup is defined in manifest,
// but kept for compatibility or if popup is removed.
await clearData(tab);
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "clearSiteData") {
clearData(sender.tab).then(() => {
sendResponse({ success: true });
}).catch((e) => {
sendResponse({ success: false, error: e.message });
});
return true; // Keep channel open
}
if (request.message === "openPopupWithAutoClear") {
chrome.action.openPopup();
sendResponse({ success: true });
return true;
}
if (request.action === "getCurrentSite") {
const tab = sender.tab;
if (tab && tab.url) {
try {
const url = new URL(tab.url);
if (["chrome:", "chrome-extension:", "moz-extension:"].includes(url.protocol) || !url.hostname) {
sendResponse({ hostname: chrome.i18n.getMessage("currentSite") });
} else {
sendResponse({ hostname: url.hostname, favIconUrl: tab.favIconUrl });
}
} catch (e) {
sendResponse({ hostname: chrome.i18n.getMessage("currentSite") });
}
} else {
sendResponse({ hostname: chrome.i18n.getMessage("currentSite") });
}
return true;
}
if (request.action === "clearDataFromPopup") {
const tab = request.tab || sender.tab;
if (tab && tab.url) {
clearData(tab, request.settings).then(() => {
sendResponse({ success: true });
}).catch((e) => {
sendResponse({ success: false, error: e.message });
});
} else {
sendResponse({ success: false, error: "Unable to determine the current site" });
}
return true;
}
});
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
chrome.storage.local.set(DEFAULT_SETTINGS);
const installDate = new Date().toISOString();
chrome.storage.sync.set({ installDate });
}
});