-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
64 lines (55 loc) · 1.7 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
var currentHost = "";
var lastInterval = null;
var database = null;
chrome.runtime.onInstalled.addListener(function() {
lastInterval = new Date().getTime();
database = new TimeDatabase();
});
async function changeWebpage(newHost) {
if (currentHost == newHost)
return;
currentHost = newHost;
lastInterval = new Date().getTime();
}
async function onFocusLost() {
if (currentHost == "")
return;
// Don't record intervals less than 10 seconds
if (new Date().getTime() - lastInterval >= 10000) {
database.insertBlock({
host: currentHost,
startTime: lastInterval,
endTime: new Date().getTime(),
});
}
currentHost = "";
lastInterval = new Date().getTime();
}
// Prepare the data to send to the frontend
async function generateData(duration) {
let responseData = await database.getDataInRange(duration);
return responseData;
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.command == "deleteData") {
database.deleteDatabase();
database.createDatabase();
sendResponse("Data deleted.");
} else if (request.command == "pageFocused") {
changeWebpage(request.page);
} else if (request.command == "pageBlurred") {
onFocusLost();
} else if (request.command == "newPage") {
changeWebpage(request.page);
} else if (request.command == "getDayData") {
generateData(database.DAY).then(sendResponse);
} else if (request.command == "getWeekData") {
generateData(database.WEEK).then(sendResponse);
} else if (request.command == "getMonthData") {
generateData(database.MONTH).then(sendResponse);
} else {
console.error("Unknown command:", request.command);
}
// Important! Return true to indicate you want to send a response asynchronously
return true;
});