-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
69 lines (61 loc) · 2.02 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
const CSS = ".rc-ItemHeader { display: none; } .rc-ItemNavigation { top: 0; }";
const TITLE_APPLY = "Apply CSS";
const TITLE_REMOVE = "Remove CSS";
const APPLICABLE_PROTOCOLS = ["http:", "https:"];
/*
Toggle CSS: based on the current title, insert or remove the CSS.
Update the page action's title and icon to reflect its state.
*/
function toggleCSS(tab) {
function gotTitle(title) {
if (title === TITLE_APPLY) {
browser.pageAction.setIcon({tabId: tab.id, path: "icons/on.svg"});
browser.pageAction.setTitle({tabId: tab.id, title: TITLE_REMOVE});
browser.tabs.insertCSS({code: CSS});
} else {
browser.pageAction.setIcon({tabId: tab.id, path: "icons/off.svg"});
browser.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY});
browser.tabs.removeCSS({code: CSS});
}
}
var gettingTitle = browser.pageAction.getTitle({tabId: tab.id});
gettingTitle.then(gotTitle);
}
/*
Returns true only if the URL's protocol is in APPLICABLE_PROTOCOLS.
*/
function protocolIsApplicable(url) {
var anchor = document.createElement('a');
anchor.href = url;
return APPLICABLE_PROTOCOLS.includes(anchor.protocol);
}
/*
Initialize the page action: set icon and title, then show.
Only operates on tabs whose URL's protocol is applicable.
*/
function initializePageAction(tab) {
if (tab.url.includes("www.coursera.org") && protocolIsApplicable(tab.url)) {
browser.pageAction.setIcon({tabId: tab.id, path: "icons/off.svg"});
browser.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY});
browser.pageAction.show(tab.id);
}
}
/*
When first loaded, initialize the page action for all tabs.
*/
var gettingAllTabs = browser.tabs.query({});
gettingAllTabs.then((tabs) => {
for (let tab of tabs) {
initializePageAction(tab);
}
});
/*
Each time a tab is updated, reset the page action for that tab.
*/
browser.tabs.onUpdated.addListener((id, changeInfo, tab) => {
initializePageAction(tab);
});
/*
Toggle CSS when the page action is clicked.
*/
browser.pageAction.onClicked.addListener(toggleCSS);