-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
350 lines (306 loc) · 9.34 KB
/
background.js
File metadata and controls
350 lines (306 loc) · 9.34 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// This function is preserved for backward compatibility
// (in case the user clicks the extension icon without the popup)
function getDomainAndTLD(url) {
const urlObj = new URL(url);
const parts = urlObj.hostname.split(".");
if (parts.length > 2) {
return parts.slice(-2).join(".");
}
return urlObj.hostname;
}
// Create context menus on extension installation
chrome.runtime.onInstalled.addListener(() => {
// Set badge color
chrome.action.setBadgeBackgroundColor({ color: "#4a90e2" });
// Create parent context menu
chrome.contextMenus.create({
id: "session-cleaner",
title: "Session Cleaner",
contexts: ["page", "selection", "link"],
});
// Create sub-menus for different cleaning options
chrome.contextMenus.create({
id: "clean-all",
parentId: "session-cleaner",
title: "🧹 Clean All Data",
contexts: ["page", "selection", "link"],
});
chrome.contextMenus.create({
id: "clean-cookies",
parentId: "session-cleaner",
title: "🍪 Clean Cookies Only",
contexts: ["page", "selection", "link"],
});
chrome.contextMenus.create({
id: "clean-storage",
parentId: "session-cleaner",
title: "💾 Clean Storage Only",
contexts: ["page", "selection", "link"],
});
chrome.contextMenus.create({
id: "separator-1",
parentId: "session-cleaner",
type: "separator",
contexts: ["page", "selection", "link"],
});
chrome.contextMenus.create({
id: "clean-with-reload",
parentId: "session-cleaner",
title: "🔄 Clean and Reload Page",
contexts: ["page", "selection", "link"],
});
});
// Listen for context menu clicks
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (!tab) return;
switch (info.menuItemId) {
case "clean-all":
performContextMenuCleanup(tab, {
cookies: true,
localStorage: true,
sessionStorage: true,
indexedDB: true,
autoReload: false,
});
break;
case "clean-cookies":
performContextMenuCleanup(tab, {
cookies: true,
localStorage: false,
sessionStorage: false,
indexedDB: false,
autoReload: false,
});
break;
case "clean-storage":
performContextMenuCleanup(tab, {
cookies: false,
localStorage: true,
sessionStorage: true,
indexedDB: true,
autoReload: false,
});
break;
case "clean-with-reload":
performContextMenuCleanup(tab, {
cookies: true,
localStorage: true,
sessionStorage: true,
indexedDB: true,
autoReload: true,
});
break;
}
});
// Function to perform cleanup from context menu
function performContextMenuCleanup(tab, preferences) {
const domain = getDomainAndTLD(tab.url);
const cleanupResults = {
cookies: 0,
localStorage: 0,
sessionStorage: 0,
indexedDB: 0,
};
// Show notification that cleaning is starting
chrome.action.setBadgeText({ text: "Cleaning", tabId: tab.id });
// Clean cookies if enabled
if (preferences.cookies) {
chrome.cookies.getAll({ domain: domain }, (cookies) => {
cleanupResults.cookies = cookies.length;
for (let cookie of cookies) {
const cookieUrl = `http${cookie.secure ? "s" : ""}://${cookie.domain}${
cookie.path
}`;
chrome.cookies.remove({ url: cookieUrl, name: cookie.name });
}
});
}
// Clean storage if enabled
if (
preferences.localStorage ||
preferences.sessionStorage ||
preferences.indexedDB
) {
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
function: clearStoragesFromContext,
args: [preferences],
},
(results) => {
if (results && results[0]) {
const result = results[0].result;
cleanupResults.localStorage = result.localStorage;
cleanupResults.sessionStorage = result.sessionStorage;
cleanupResults.indexedDB = result.indexedDB;
}
// Save to history
saveContextMenuHistory(tab.url, cleanupResults, preferences);
// Show completion notification
chrome.action.setBadgeText({ text: "Done", tabId: tab.id });
setTimeout(() => {
chrome.action.setBadgeText({ text: "", tabId: tab.id });
}, 2000);
// Auto reload if enabled
if (preferences.autoReload) {
setTimeout(() => {
chrome.tabs.reload(tab.id);
}, 1000);
}
}
);
} else {
// If only cookies were cleaned, show completion immediately
saveContextMenuHistory(tab.url, cleanupResults, preferences);
chrome.action.setBadgeText({ text: "Done", tabId: tab.id });
setTimeout(() => {
chrome.action.setBadgeText({ text: "", tabId: tab.id });
}, 2000);
}
}
// Function to clear storages from context menu
function clearStoragesFromContext(preferences) {
const result = {
localStorage: 0,
sessionStorage: 0,
indexedDB: 0,
};
// Clear localStorage
if (preferences.localStorage) {
result.localStorage = localStorage.length;
localStorage.clear();
}
// Clear sessionStorage
if (preferences.sessionStorage) {
result.sessionStorage = sessionStorage.length;
sessionStorage.clear();
}
// Clear IndexedDB
if (preferences.indexedDB && window.indexedDB) {
window.indexedDB.databases().then((dbs) => {
result.indexedDB = dbs.length;
dbs.forEach((db) => {
window.indexedDB.deleteDatabase(db.name);
});
});
}
return result;
}
// Function to save context menu cleaning to history
function saveContextMenuHistory(url, results, preferences) {
chrome.storage.local.get(["cleaningHistory"], (result) => {
const history = result.cleaningHistory || [];
const historyEntry = {
url: url,
results: results,
preferences: preferences,
timestamp: Date.now(),
mode: "context-menu",
};
// Add new entry to beginning
history.unshift(historyEntry);
// Keep only last 50 entries
const limitedHistory = history.slice(0, 50);
chrome.storage.local.set({ cleaningHistory: limitedHistory });
});
}
// Listen for messages from popup.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "getTabInfo") {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs.length > 0) {
sendResponse({ url: tabs[0].url, tabId: tabs[0].id });
} else {
sendResponse({ error: "No active tab found" });
}
});
return true; // Required for async sendResponse
}
});
// Legacy support: If the user clicks the extension icon directly (when popup is disabled)
chrome.action.onClicked.addListener((tab) => {
// Only handle clicks if we couldn't show the popup for some reason
if (!chrome.action.getPopup) {
legacyCleanup(tab);
}
});
// Function to handle the legacy cleaning process
function legacyCleanup(tab) {
const domain = getDomainAndTLD(tab.url);
// Check if auto-reload is enabled in preferences
chrome.storage.local.get(["cleanPreferences"], (result) => {
const autoReload = result.cleanPreferences?.autoReload || false;
// Clear cookies
chrome.cookies.getAll({ domain: domain }, (cookies) => {
for (let cookie of cookies) {
const cookieUrl = `http${cookie.secure ? "s" : ""}://${cookie.domain}${
cookie.path
}`;
chrome.cookies.remove({ url: cookieUrl, name: cookie.name });
}
});
// Clear local storage, session storage, and IndexedDB
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
function: (shouldReload) => {
// Clear localStorage
localStorage.clear();
// Clear sessionStorage
sessionStorage.clear();
// Clear IndexedDB
if (window.indexedDB) {
window.indexedDB.databases().then((dbs) => {
dbs.forEach((db) => {
window.indexedDB.deleteDatabase(db.name);
});
});
}
// Force a page reload to ensure all changes take effect (only if auto-reload is enabled)
if (shouldReload) {
location.reload();
}
},
args: [autoReload],
},
() => {
// Save to history for legacy mode
saveLegacyHistory(tab.url);
// Show a notification to the user
chrome.action.setBadgeText({ text: "Done", tabId: tab.id });
setTimeout(() => {
chrome.action.setBadgeText({ text: "", tabId: tab.id });
}, 2000);
}
);
});
}
// Function to save legacy cleaning to history
function saveLegacyHistory(url) {
chrome.storage.local.get(["cleaningHistory"], (result) => {
const history = result.cleaningHistory || [];
const historyEntry = {
url: url,
results: {
cookies: 0, // We don't have exact count in legacy mode
localStorage: 0,
sessionStorage: 0,
indexedDB: 0,
},
preferences: {
cookies: true,
localStorage: true,
sessionStorage: true,
indexedDB: true,
autoReload: false,
},
timestamp: Date.now(),
mode: "legacy",
};
// Add new entry to beginning
history.unshift(historyEntry);
// Keep only last 50 entries
const limitedHistory = history.slice(0, 50);
chrome.storage.local.set({ cleaningHistory: limitedHistory });
});
}