-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
89 lines (75 loc) · 2.16 KB
/
background.js
File metadata and controls
89 lines (75 loc) · 2.16 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// let currentTab;
// let currentTabId;
let injected = false; // set to true after first time code injection
// Retrieve the action badge to check if the extension is 'ON' or 'OFF'
let prevState;
// Next state will always be the opposite
let nextState;
// function getCurrentTab() {
// chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
// console.log(tabs[0]);
// currentTabId = tabs[0].id;
// });
// }
// Set the action badge to the next state
async function setBadgeState(tab) {
await chrome.action.setBadgeText({
tabId: tab.id,
text: nextState,
});
}
// state ON
function stateOn(tab) {
console.log(`is injected: ${injected}`);
if (!injected) {
chrome.scripting
.executeScript({
target: { tabId: tab.id },
files: ["util.js"],
})
.then(() => {
console.log("injected util.js");
injected = true;
});
} else {
console.log("already injected util.js");
}
}
// function stateOff(tab){
// // no code yet
// }
// send nextState to util.js
async function sendNextState(tab) {
const response = await chrome.tabs.sendMessage(tab.id, {
status: nextState,
});
// do something with response here, not outside the function
console.log(response);
}
// luister naar de status van de badge (onclick)
function onClickAddListener() {
chrome.action.onClicked.addListener(async (tab) => {
// Retrieve the action badge to check if the extension is 'ON' or 'OFF'
prevState = await chrome.action.getBadgeText({ tabId: tab.id });
// Next state will always be the opposite
nextState = prevState === "ON" ? "OFF" : "ON";
setBadgeState(tab);
nextState === "ON" && stateOn(tab);
// nextState === "OFF" && stateOff(tab);
sendNextState(tab);
});
}
// zet de initiele status op de badge
function onInstalledAddListener() {
chrome.runtime.onInstalled.addListener(() => {
chrome.action.setBadgeText({
text: "OFF",
});
});
}
// MAIN CODE ===============
if (!injected) {
// listeners are added once
onClickAddListener();
onInstalledAddListener();
}