-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
110 lines (96 loc) · 3.11 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
109
110
let activeTabId = null;
let activeTimer = null;
function resetDailyUsage() {
const today = new Date().toDateString();
chrome.storage.sync.get(['lastResetDay'], (result) => {
if (result.lastResetDay !== today) {
chrome.storage.sync.set({ timeSpent: 0, lastResetDay: today });
}
});
}
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({
timeLimit: 5, // Default time limit: 5 minutes
timeSpent: 0,
lastResetDay: new Date().toDateString(),
isActive: false
});
});
chrome.tabs.onActivated.addListener((activeInfo) => {
chrome.tabs.get(activeInfo.tabId, (tab) => {
if (tab.url && tab.url.includes('facebook.com')) {
activeTabId = tab.id;
resetDailyUsage();
startActiveTimer();
} else {
activeTabId = null;
stopActiveTimer();
}
});
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.url && tab.url.includes('facebook.com')) {
activeTabId = tabId;
resetDailyUsage();
startActiveTimer();
}
});
function startActiveTimer() {
if (!activeTimer) {
activeTimer = setInterval(() => {
chrome.storage.sync.get(['timeSpent', 'timeLimit'], (result) => {
const newTimeSpent = result.timeSpent + 1;
chrome.storage.sync.set({ timeSpent: newTimeSpent });
updatePopup(); // Update the popup every second
if (newTimeSpent >= result.timeLimit * 60) {
if (activeTabId) {
chrome.tabs.sendMessage(activeTabId, { action: "showOverlay" });
}
stopActiveTimer();
}
});
}, 1000);
}
}
function stopActiveTimer() {
if (activeTimer) {
clearInterval(activeTimer);
activeTimer = null;
}
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "leaveFacebook") {
chrome.tabs.create({ url: 'about:newtab' }, () => {
if (sender.tab && sender.tab.id) {
chrome.tabs.remove(sender.tab.id);
}
});
stopActiveTimer();
} else if (request.action === "setActive") {
if (sender.tab && sender.tab.id === activeTabId) {
if (request.isActive) {
startActiveTimer();
} else {
stopActiveTimer();
}
}
} else if (request.action === "pageLoaded") {
if (sender.tab && sender.tab.url && sender.tab.url.includes('facebook.com')) {
activeTabId = sender.tab.id;
resetDailyUsage();
}
}
});
function updatePopup() {
chrome.storage.sync.get(['timeSpent'], (result) => {
chrome.runtime.sendMessage({
action: "updateTimeSpent",
timeSpent: result.timeSpent || 0
});
});
}
chrome.action.onClicked.addListener((tab) => {
updatePopup();
});
// Check and reset daily usage every hour
setInterval(resetDailyUsage, 3600000);