-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
58 lines (53 loc) · 1.53 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
let isBlocking = false;
let sitesToBlock = [];
let redirectUrl = '';
// Load initial state
browser.storage.local.get(['isBlocking', 'sites', 'redirectUrl'], function(result) {
isBlocking = result.isBlocking || false;
sitesToBlock = result.sites || [];
redirectUrl = result.redirectUrl || '';
updateIcon(isBlocking);
});
// Listen for changes in storage
browser.storage.onChanged.addListener(function(changes, areaName) {
if (areaName === 'local') {
if (changes.isBlocking) {
isBlocking = changes.isBlocking.newValue;
updateIcon(isBlocking);
}
if (changes.sites) {
sitesToBlock = changes.sites.newValue;
}
if (changes.redirectUrl) {
redirectUrl = changes.redirectUrl.newValue;
}
}
});
// Listen for messages from popup
browser.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === 'updateBlocking') {
isBlocking = request.isBlocking;
updateIcon(isBlocking);
}
});
// Web request listener
browser.webRequest.onBeforeRequest.addListener(
function(details) {
if (isBlocking) {
const url = new URL(details.url);
if (sitesToBlock.some(site => url.hostname.includes(site))) {
if (redirectUrl) {
return { redirectUrl: redirectUrl };
}
return { cancel: true };
}
}
return { cancel: false };
},
{urls: ["<all_urls>"]},
["blocking"]
);
function updateIcon(isBlocking) {
const iconPath = isBlocking ? 'icon_active.png' : 'icon.png';
browser.browserAction.setIcon({ path: iconPath });
}