-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
95 lines (77 loc) · 2.62 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
// create alarm instead of setTimeout
chrome.alarms.create({ when: Date.now() + 50000 });
// get a list of created time of all tabs
chrome.tabs.onCreated.addListener(addTabToStorage);
const getCurrentTime = () => {
const date = new Date();
return date.getTime();
};
function addTabToStorage(tab) {
const payload = { id: tab.id, startTime: getCurrentTime() };
chrome.storage.local.get(["initialTime"], function (result) {
const initialTime = result.initialTime;
if (!initialTime) {
chrome.storage.local.set({ initialTime: [payload] });
}
initialTime.push(payload);
chrome.storage.local.set({ initialTime });
});
}
// reset start time when moved back to the tab
chrome.tabs.onActivated.addListener(resetStartTime);
async function resetStartTime(tab) {
chrome.storage.local.get(["initialTime"], function (result) {
const initialTime = result.initialTime;
initialTime.map((tabs) => {
if (tab.tabId === tabs.id) {
tabs.startTime = getCurrentTime();
return tabs;
}
return tabs;
});
chrome.storage.local.set({ initialTime });
});
}
// check at an interval of 50 seconds if the tab is inactive for the closing time
chrome.alarms.onAlarm.addListener((alarm) => {
// get the time stored in local storage
chrome.storage.local.get(["time", "initialTime"], async function (result) {
let time = result.time;
let initialTime = result.initialTime || [];
// if time not set then set the time and assign default 5 seconds to closing time
if (!time) {
chrome.storage.local.set({ time: 5 });
time = 5;
}
let closingTime = time * 60000;
let urlMathcher = await chrome.tabs.query({
url: "https://meet.google.com/*",
});
let activeTabs = await chrome.tabs.query({ active: true });
const refreshTimingForTabs = [...activeTabs, ...urlMathcher];
initialTime = initialTime.map((tabs) => {
// check for current active tabs and reset its time to current
refreshTimingForTabs.forEach((element) => {
if (element.id == tabs.id) {
tabs.startTime = getCurrentTime();
return tabs;
}
});
return tabs;
});
const date = new Date();
const timeInSeconds = date.getTime();
initialTime = initialTime.filter((tabs) => {
let timeDifference = timeInSeconds - tabs.startTime;
if (timeDifference > closingTime) {
const isTabPresent = await chrome.tabs.get(tabs.id);
if (isTabPresent) {
chrome.tabs.remove(tabs.id);
}
return false;
}
return true;
});
});
chrome.alarms.create({ when: Date.now() + 50000 });
});