-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
75 lines (63 loc) · 3.01 KB
/
background.js
File metadata and controls
75 lines (63 loc) · 3.01 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
let tabsManaged = [];
function noop() {}
function getDomainFromUrl(url) {
let urlObj = (new URL(url));
return urlObj.hostname.replace('www.','').toLowerCase();
}
chrome.tabs.onUpdated.addListener((currentTabId, updatedTab) => {
if (!tabsManaged.includes(currentTabId) && updatedTab.url) {
tabsManaged.push(currentTabId);
let tabGroupInfo = {};
let currentGroupId;
chrome.tabGroups.query({}, function(tabGroups) {
chrome.tabs.query({ /* groupId: tabGroup.id */ }, function (tabs) {
tabGroups.forEach(function(tabGroup) {
let tabsInGroup = tabs.filter(function(tab) {
return tab.groupId === tabGroup.id;
});
let firstUrl = (tabsInGroup.find(function(tab) {
return !!tab.url;
}) || {}).url;
let domain = firstUrl && getDomainFromUrl(firstUrl);
tabGroupInfo[tabGroup.id] = {
name: tabGroup.title,
tabs: tabsInGroup,
isSameDomain: tabsInGroup.every(function(tab) {
if (!tab.url) {
// Ignore tabs that don't have any url yet
return true;
}
if (tab.id === currentTabId) {
// Ignore the tab we just opened
currentGroupId = tabGroup.id;
return true;
}
if (!domain) {
// First result becomes the domain for the group
domain = getDomainFromUrl(tab.url);
return true;
}
return domain === getDomainFromUrl(tab.url);
})
};
if (tabGroupInfo[tabGroup.id].isSameDomain) {
tabGroupInfo[tabGroup.id].domain = domain;
}
});
let updatedDomain = getDomainFromUrl(updatedTab.url);
let matchingGroupId = Object.keys(tabGroupInfo).find(function(tabGroupId) {
return tabGroupInfo[tabGroupId].domain === updatedDomain;
});
if (matchingGroupId) {
//Add tab to group
chrome.tabs.group({ groupId: Number(matchingGroupId), tabIds: currentTabId }, noop);
//Expand group if it's collapse to avoid dark pattern
chrome.tabGroups.update(Number(matchingGroupId), { collapsed: false }, noop);
} else if (tabGroupInfo[currentGroupId] && tabGroupInfo[currentGroupId].isSameDomain) {
//Remove tab from group
chrome.tabs.ungroup(currentTabId, noop);
}
});
});
}
});