-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
108 lines (91 loc) · 2.79 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
let tabData = {};
let tabDomainMap = {};
getTabDataFromStorage();
chrome.tabs.onActivated.addListener((activeInfo) => {
const tabId = activeInfo.tabId;
const currentTime = new Date().getTime();
chrome.tabs.get(tabId, (tab) => {
const url = tab.url;
const domain = extractDomain(url);
tabDomainMap[tabId] = domain;
if (!tabData[domain]) {
tabData[domain] = {
startTime: currentTime,
totalTime: 0,
url: url
}
saveTabDataToStorage();
}
});
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
const domain = tabDomainMap[tabId];
const currentTabUrl = tab.url;
const previousTabUrl = tabData[domain] && tabData[domain].url;
if (currentTabUrl && previousTabUrl && currentTabUrl !== previousTabUrl) {
const changedDomain = extractDomain(tab.url);
if (domain === changedDomain) {
tabData[domain].url = changeInfo.url;
tabData[domain].startTime = Date.now();
}
else {
tabDomainMap[tabId] = changedDomain;
if (!tabData[changedDomain]) {
tabData[changedDomain] = {
startTime: Date.now(),
totalTime: 0,
url: tab.url
}
saveTabDataToStorage();
}
}
}
});
function saveTabDataToStorage() {
chrome.storage.local.set({ 'tabData': tabData }, () => {});
}
function getTabDataFromStorage() {
chrome.storage.local.get(['tabData'], function(result) {
tabData = result.tabData || {};
});
}
function deleteTabDataFromStorage(domain) {
if (tabData[domain]) {
delete tabData[domain];
saveTabDataToStorage();
}
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "getTabData") {
sendResponse(tabData);
}
if (request.action === "deleteDomain") {
deleteTabDataFromStorage(request.domain)
return true;
}
});
function extractDomain(url) {
if (url === "") {
return "newtab";
}
if (url.startsWith('chrome://')) {
const parts = url.split('/');
return parts[2] || null;
}
const matches = url.match(/^https?:\/\/([^\/?#]+)(?:[\/?#]|$)|^[^:]+/i);
return matches && matches[1];
}
function updateTotalTime() {
chrome.tabs.query({ active: true }, activeTabs => {
if (activeTabs.length === 0) {
clearInterval(intervalId);
}
activeTabs.forEach(tab => {
const tabDomain = extractDomain(tab.url);
if (tabData[tabDomain]) {
tabData[tabDomain].totalTime += 1;
}
});
});
}
intervalId = setInterval(updateTotalTime, 1000);