-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
147 lines (94 loc) · 2.75 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
var currentTab;
var inStash;
/*
* Updates the browserAction icon to reflect whether the current page
* is already in the stash
*/
function updateIcon() {
browser.pageAction.setIcon({
path: inStash ? {
19: "icons/star-filled-19.png",
38: "icons/star-filled-38.png"
} : {
19: "icons/star-empty-19.png",
38: "icons/star-empty-38.png"
},
tabId: currentTab.id
});
}
function getRandom() {
let gettingItem = browser.storage.local.get("URLs");
gettingItem.then(loadRand, onError);
updateIcon();
}
function loadRand(item) {
if (item.URLs.list != undefined && item.URLs.list.length > 0) {
randPage = item.URLs.list[getRandomInt(0, item.URLs.list.length)];
browser.tabs.update({
url: randPage
});
}
}
/*
* Switches currentTab and inStash to reflect the currently active tab
*/
function updateActiveTab(tabs) {
var gettingActiveTab = browser.tabs.query({
active: true,
currentWindow: true
});
gettingActiveTab.then((tabs) => {
currentTab = tabs[0];
browser.pageAction.show(tabs[0].id);
let gettingItem = browser.storage.local.get("URLs");
gettingItem.then(updateTab, onError);
});
function updateTab(item) {
if (item.URLs == undefined) {
item.URLs = {};
item.URLs.list = [];
}
if (item.URLs.list.filter(function(e){
return e == currentTab.url
}).length == 0) {
inStash = false;
updateIcon();
} else {
inStash = true;
updateIcon();
}
}
}
browser.pageAction.onClicked.addListener(function() {
let gettingItem = browser.storage.local.get("URLs");
gettingItem.then(storeURL, onError);
updateActiveTab();
});
function storeURL(item) {
if (item.URLs == undefined) {
item.URLs = {};
item.URLs.list = [];
}
if (item.URLs.list.filter(function(e){ return e == currentTab.url}).length == 0) {
item.URLs.list.push(currentTab.url);
}
else{
item.URLs.list = item.URLs.list.filter(function(e){ return e != currentTab.url});
}
browser.storage.local.set(item);
}
function onError(error) {
console.log(`Error: ${error}`);
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
browser.browserAction.onClicked.addListener(getRandom);
// listen to tab URL changes
browser.tabs.onUpdated.addListener(updateActiveTab);
// listen to tab switching
browser.tabs.onActivated.addListener(updateActiveTab);
// update when the extension loads initially
updateActiveTab();