-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
55 lines (55 loc) · 1.9 KB
/
background.js
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
// background listener
chrome.storage.sync.get("autoSortEnabled", function (data) {
if (data.autoSortEnabled) {
chrome.tabs.onCreated.addListener(onTabCreate);
chrome.tabs.onUpdated.addListener(onTabUpdate);
}
});
chrome.storage.onChanged.addListener(function (changes, areaName) {
if (areaName === "sync" && changes.autoSortEnabled) {
if (changes.autoSortEnabled.newValue) {
chrome.tabs.onCreated.addListener(onTabCreate);
chrome.tabs.onUpdated.addListener(onTabUpdate);
} else {
chrome.tabs.onCreated.removeListener(onTabCreate);
chrome.tabs.onUpdated.removeListener(onTabUpdate);
}
}
});
async function onTabCreate(tab) {
if (isValidURL(tab.url)) {
const existingTab = await findTabWithMatchingDomain(tab);
if (existingTab) {
if (existingTab.groupId >= 0) {
await chrome.tabs.group({ groupId: existingTab.groupId, tabIds: [tab.id] });
} else {
await chrome.tabs.group({ tabIds: [existingTab.id, tab.id] });
}
console.log('Tab grouped successfully');
}
}
}
async function onTabUpdate(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete' && isValidURL(tab.url)) {
const existingTab = await findTabWithMatchingDomain(tab);
if (existingTab) {
await chrome.tabs.group({ groupId: existingTab.groupId, tabIds: [tabId] });
console.log('Tab grouped successfully');
}
}
}
async function findTabWithMatchingDomain(tab) {
const tabs = await chrome.tabs.query({ currentWindow: true });
const domain = new URL(tab.url).hostname;
return tabs.find((t) => {
return new URL(t.url).hostname === domain && t.id !== tab.id;
});
}
function isValidURL(url) {
try {
new URL(url);
return true;
} catch (err) {
return false;
}
}