-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
113 lines (93 loc) · 2.7 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
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
let frequencyOfSort = 1000
let currentTabTitles = []
const URL = 'url'
// default ordering
let ordering = URL
// start sorting interval from initial state
createInterval();
function createInterval() {
interval = setInterval(function () {
sortTabs()
}, frequencyOfSort)
}
// A function to extract value as an array and compare them
function equalsCheck(arrayA, arrayB) {
// check the length
if (arrayA.length != arrayB.length) {
return false;
} else {
// comparing each element of array
for (let i = 0; i < arrayA.length; i++) {
if (arrayA[i] !== arrayB[i]) {
return false;
}
}
return true
}
}
async function moveTab(tabs, index) {
let tab = tabs[index]
if (tab != null) {
let tabId = tabs[index].id
if (tabId != null) {
try {
await chrome.tabs.move(tabId, { index: index });
console.log("Success.");
} catch (error) {
if (error == "Error: Tabs cannot be edited right now (user may be dragging a tab).") {
setTimeout(() => moveTab(tabs, index));
} else {
console.error(error);
}
}
}
}
}
function moveTabs(tabs) {
for (let index = 0; index < tabs.length; index++) {
moveTab(tabs, index)
}
}
function getValueToSortByFromOrderingSelected(tab) {
if(ordering === URL) {
return tab.url
}
if(ordering === 'title') {
return tab.title
}
}
function sortTabs() {
chrome.tabs.query({}).then(tabs => {
// only sort when the tab order has changed
let tabTitles = tabs.map(tab => tab.title)
var same = equalsCheck(currentTabTitles, tabTitles)
if (!same) {
currentTabTitles = tabTitles
const collator = new Intl.Collator();
tabs.sort((tabA, tabB) => collator.compare(getValueToSortByFromOrderingSelected(tabA), getValueToSortByFromOrderingSelected(tabB)));
moveTabs(tabs)
}
});
}
chrome.tabs.onMoved.addListener(function () {
console.log('moved tab...')
})
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.action === "updateConfiguration") {
updateConfiguration(request)
sendResponse("updated configuration");
}
if (request.action === "getFrequency") {
sendResponse({ frequency: frequencyOfSort })
}
}
);
function recreateInterval() {
clearInterval(interval)
createInterval()
}
function updateConfiguration(request) {
frequencyOfSort = request.frequency
recreateInterval()
}