-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
60 lines (52 loc) · 1.64 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
let websiteData = {};
function getWebsiteName(url) {
try {
const urlObj = new URL(url);
return urlObj.hostname;
} catch (error) {
console.error('Error processing URL:', url, error);
return 'Invalid URL';
}
}
function updateWebsiteData(tabId, url) {
const currentTimestamp = Date.now();
const websiteName = getWebsiteName(url);
if (!websiteData[tabId]) {
websiteData[tabId] = {
name: websiteName,
time: 0,
lastUpdate: currentTimestamp,
};
} else {
const lastUpdate = websiteData[tabId].lastUpdate;
websiteData[tabId].time += Math.floor((currentTimestamp - lastUpdate) / 1000);
websiteData[tabId].lastUpdate = currentTimestamp;
}
}
chrome.tabs.onActivated.addListener((activeInfo) => {
chrome.tabs.get(activeInfo.tabId, (tab) => {
updateWebsiteData(tab.id, tab.url);
});
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
updateWebsiteData(tab.id, tab.url);
}
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'getWebsiteData') {
const websiteDataArray = Object.values(websiteData);
sendResponse(websiteDataArray);
} else if (request.action === 'resetData') {
websiteData = {};
sendResponse([]);
} else if (request.action === 'updateTab') {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const currentTab = tabs[0];
updateWebsiteData(currentTab.id, currentTab.url);
});
}
});
chrome.tabs.onRemoved.addListener((tabId) => {
delete websiteData[tabId];
});