-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbackground.js
More file actions
69 lines (62 loc) · 1.8 KB
/
background.js
File metadata and controls
69 lines (62 loc) · 1.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
let startTime = null;
let currentUrl = null;
let timeData = {};
// Load timeData from storage on start
chrome.runtime.onStartup.addListener(() => {
chrome.storage.local.get(['timeData'], (result) => {
timeData = result.timeData || {};
});
});
// Track when tab is activated
chrome.tabs.onActivated.addListener((activeInfo) => {
chrome.tabs.get(activeInfo.tabId, (tab) => {
if (tab && tab.url) handleTabChange(tab.url);
});
});
// Track when tab URL changes
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.url) {
handleTabChange(changeInfo.url);
}
});
// Track when tab is closed
chrome.tabs.onRemoved.addListener(() => {
handleTabChange(null);
});
// Handle tab switch or close
function handleTabChange(newUrl) {
if (currentUrl && startTime) {
try {
const domain = new URL(currentUrl).hostname;
const timeSpent = Date.now() - startTime;
timeData[domain] = (timeData[domain] || 0) + timeSpent;
chrome.storage.local.set({ timeData });
} catch (e) {
console.error('Error tracking time for previous tab:', e);
}
}
if (newUrl) {
currentUrl = newUrl;
startTime = Date.now();
} else {
currentUrl = null;
startTime = null;
}
}
// Respond to popup request
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'getCurrentTimes') {
const currentTimes = { ...timeData };
if (currentUrl && startTime) {
try {
const domain = new URL(currentUrl).hostname;
const currentTime = Date.now() - startTime;
currentTimes[domain] = (currentTimes[domain] || 0) + currentTime;
} catch (e) {
console.error('Error getting current tab domain:', e);
}
}
sendResponse(currentTimes);
return true; // keep message channel open
}
});