-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
87 lines (71 loc) · 2.8 KB
/
background.js
File metadata and controls
87 lines (71 loc) · 2.8 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
76
77
78
79
80
81
82
83
84
85
86
87
let activeTabId = null;
let activeStartTime = 0;
let tabTimes = {};
function updateTabTime(tabId, endTime) {
if (activeTabId === null || activeStartTime === 0) return;
const elapsed = endTime - activeStartTime;
console.log("Updating tab time. Tab ID:", tabId, "Elapsed Time:", elapsed);
if (!tabTimes[tabId]) {
tabTimes[tabId] = 0;
}
tabTimes[tabId] += elapsed;
chrome.storage.local.set({ tabTimes }, () => {
console.log("Tab times saved to storage:", tabTimes);
});
// Reset the start time for continuous tracking
activeStartTime = endTime;
}
chrome.tabs.onActivated.addListener(activeInfo => {
const currentTime = Date.now();
updateTabTime(activeTabId, currentTime);
activeTabId = activeInfo.tabId;
activeStartTime = currentTime;
console.log("Tab Activated. New Tab ID:", activeTabId, "Start Time:", activeStartTime);
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (tabId === activeTabId && changeInfo.status === 'complete') {
const currentTime = Date.now();
updateTabTime(activeTabId, currentTime);
activeStartTime = currentTime;
console.log("Tab Updated. Tab ID:", tabId, "Start Time reset to:", activeStartTime);
}
});
chrome.windows.onFocusChanged.addListener(windowId => {
const currentTime = Date.now();
if (activeTabId !== null && windowId === chrome.windows.WINDOW_ID_NONE) {
updateTabTime(activeTabId, currentTime);
console.log("Window lost focus. Tab ID:", activeTabId, "Time updated.");
activeTabId = null;
activeStartTime = 0;
} else if (windowId !== chrome.windows.WINDOW_ID_NONE) {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
if (tabs.length > 0) {
updateTabTime(activeTabId, currentTime);
activeTabId = tabs[0].id;
activeStartTime = currentTime;
console.log("Window regained focus. Active Tab ID:", activeTabId, "Start Time:", activeStartTime);
}
});
}
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "getActiveTime" && request.tabId === activeTabId) {
const currentTime = Date.now();
const activeTime = currentTime - activeStartTime;
sendResponse({activeTime: activeTime});
}
return true;
});
chrome.runtime.onInstalled.addListener(() => {
console.log("Extension installed or updated");
chrome.storage.local.set({ tabTimes: {} }, () => {
console.log("Initial storage set");
});
chrome.action.setBadgeText({text: 'ON'});
});
chrome.storage.local.get(['tabTimes'], (result) => {
if (result.tabTimes) {
tabTimes = result.tabTimes;
console.log("Loaded saved tab times:", tabTimes);
}
});