-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
98 lines (72 loc) · 2.15 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
var tabUrl;
var tabId;
var currentState = "active";
var visibilityState = "visible";
resetStorage();
// Check to see if local storage already exists
chrome.storage.sync.get(["timeStorage"], function(items){
console.log(items['timeStorage']);
if (items['timeStorage'] === undefined) {
chrome.storage.sync.set({ "timeStorage": {} }, function(){});
}
});
// Called every second
setInterval(function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabArray) {
var tabData = tabArray[0];
// If the tab isn't valid (usually the chrome console)
if (tabData == null){
tabUrl = "none";
}
// If the tab is valid, retrieve its url and id
else{
tabUrl = tabData.url;
tabId = tabData.id;
}
if (isGoogleDoc(tabUrl)){
var tabUrlShortened = parseDocsUrl(tabUrl);
// If docs tab is not in storage
chrome.storage.sync.get(["timeStorage"], function(items){
if (!(tabUrlShortened in items['timeStorage'])){
items['timeStorage'][tabUrlShortened] = {};
}
chrome.idle.queryState(30, function(status){
currentState = status;
});
chrome.tabs.sendMessage(tabId, {visibilityRequest: "true"}, function(visibility){
visibilityState = visibility;
});
console.log(visibilityState);
if(currentState == 'active' && visibilityState == 'visible'){
items['timeStorage'][tabUrlShortened] += 1;
}
chrome.tabs.sendMessage(tabId, {time: items['timeStorage'][tabUrlShortened], state: currentState});
chrome.storage.sync.set({ "timeStorage": items['timeStorage'] }, function(){});
});
printStorage();
}
}
);}, 1000);
// Components
function isGoogleDoc(url){
if (url.includes("/edit")){
return true;
}
else {
return false;
}
}
function parseDocsUrl(url){
var start = url.indexOf('/d/');
var parsed = url.substring(start + 3, start + 47);
return parsed;
}
function resetStorage(){
chrome.storage.sync.set({ "timeStorage": {} }, function(){});
}
function printStorage(){
// For debugging, print timeStorage every second
chrome.storage.sync.get(["timeStorage"], function(items){
console.log(items['timeStorage']);
});
}