-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
190 lines (157 loc) · 5.54 KB
/
background.js
File metadata and controls
190 lines (157 loc) · 5.54 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
// Color palette for tab groups
const GROUP_COLORS = ['blue', 'red', 'yellow', 'green', 'pink', 'purple', 'cyan', 'orange'];
// Extract domain from URL
function getDomain(url) {
try {
const urlObj = new URL(url);
// Return hostname without 'www.' prefix for cleaner group names
return urlObj.hostname.replace(/^www\./, '');
} catch {
return 'other';
}
}
// Get a friendly short name for the domain/subdomain
function getGroupName(domain) {
const parts = domain.split('.');
// For subdomains like mail.google.com, docs.google.com - use the subdomain as name
// Examples: mail.google.com -> Mail, docs.google.com -> Docs
if (parts.length >= 3) {
const subdomain = parts[0];
// Skip generic subdomains, use parent domain instead
if (['www', 'app', 'api', 'm', 'mobile'].includes(subdomain)) {
return parts[1].charAt(0).toUpperCase() + parts[1].slice(1);
}
return subdomain.charAt(0).toUpperCase() + subdomain.slice(1);
}
// For regular domains, remove common TLDs and capitalize
const shortName = domain
.replace(/\.(com|org|net|io|dev|co|app)$/, '')
.split('.')
.pop();
return shortName.charAt(0).toUpperCase() + shortName.slice(1);
}
// Assign a consistent color based on domain hash
function getColorForDomain(domain) {
let hash = 0;
for (let i = 0; i < domain.length; i++) {
hash = ((hash << 5) - hash) + domain.charCodeAt(i);
hash = hash & hash; // Convert to 32-bit integer
}
return GROUP_COLORS[Math.abs(hash) % GROUP_COLORS.length];
}
// Sort tabs by domain and create groups
async function sortAndGroupTabs() {
// Get all tabs in the current window
const tabs = await chrome.tabs.query({ currentWindow: true });
// Skip chrome:// and edge:// internal pages
const validTabs = tabs.filter(tab =>
tab.url &&
!tab.url.startsWith('chrome://') &&
!tab.url.startsWith('edge://') &&
!tab.url.startsWith('chrome-extension://')
);
if (validTabs.length === 0) {
return { groupCount: 0, tabCount: 0 };
}
// Group tabs by domain
const domainGroups = new Map();
for (const tab of validTabs) {
const domain = getDomain(tab.url);
if (!domainGroups.has(domain)) {
domainGroups.set(domain, []);
}
domainGroups.get(domain).push(tab.id);
}
// Sort domains by number of tabs (more tabs first)
const sortedDomains = [...domainGroups.entries()]
.sort((a, b) => b[1].length - a[1].length);
let createdGroups = 0;
// Create Chrome tab groups
for (const [domain, tabIds] of sortedDomains) {
// Only create groups for domains with 2+ tabs (skip single tabs)
if (tabIds.length >= 2) {
try {
// First, move tabs to be adjacent
await chrome.tabs.move(tabIds, { index: -1 });
// Create the group
const groupId = await chrome.tabs.group({ tabIds });
// Update group properties
await chrome.tabGroups.update(groupId, {
title: getGroupName(domain),
color: getColorForDomain(domain),
collapsed: true // Always collapse groups for cleaner view
});
createdGroups++;
} catch (error) {
console.error(`Failed to group tabs for ${domain}:`, error);
}
}
}
return {
groupCount: createdGroups,
tabCount: validTabs.length
};
}
// Save all tabs to storage
async function saveTabs() {
const tabs = await chrome.tabs.query({ currentWindow: true });
// Filter and map tabs to save essential data
const tabsToSave = tabs
.filter(tab =>
tab.url &&
!tab.url.startsWith('chrome://') &&
!tab.url.startsWith('edge://') &&
!tab.url.startsWith('chrome-extension://')
)
.map(tab => ({
url: tab.url,
title: tab.title || 'Untitled',
favIconUrl: tab.favIconUrl || ''
}));
// Save with timestamp
const session = {
tabs: tabsToSave,
savedAt: new Date().toISOString(),
tabCount: tabsToSave.length
};
await chrome.storage.local.set({ savedSession: session });
return { tabCount: tabsToSave.length };
}
// Load saved tabs
async function loadTabs() {
const result = await chrome.storage.local.get('savedSession');
if (!result.savedSession || !result.savedSession.tabs) {
return { tabCount: 0 };
}
const { tabs } = result.savedSession;
// Open each saved tab
for (const tab of tabs) {
try {
await chrome.tabs.create({
url: tab.url,
active: false // Don't switch focus to each new tab
});
} catch (error) {
console.error(`Failed to open tab: ${tab.url}`, error);
}
}
return { tabCount: tabs.length };
}
// Message handler
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
const handlers = {
sortAndGroup: sortAndGroupTabs,
saveTabs: saveTabs,
loadTabs: loadTabs
};
const handler = handlers[message.action];
if (handler) {
handler()
.then(result => sendResponse(result))
.catch(error => sendResponse({ error: error.message }));
// Return true to indicate async response
return true;
}
sendResponse({ error: 'Unknown action' });
return false;
});