-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcustomcss.js
More file actions
72 lines (63 loc) · 2.25 KB
/
Copy pathcustomcss.js
File metadata and controls
72 lines (63 loc) · 2.25 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
"use strict";
// When page loads, call function to get CSS from storage
update();
// When custom CSS is changed this function is called.
// Extracts the CSS as a string and calls apply()
function update(changes) {
browser.storage.local.get().then(onGot, onError);
}
// Error checking when obtaining CSS from storage
function onError(error) {
console.info("An error occurred: ", error);
}
// Defines a listener for the storage for when custom CSS changes in Options
browser.storage.local.onChanged.addListener(update);
// Get CSS and whitelist/blacklist from storage object and call apply()
function onGot(items) {
if (items.customCSSObj !== null) {
apply(items.customCSSObj, items.whitelist, items.blacklist);
}
}
// Takes in a String parameter of the CSS code and applies it to the DOM
// or updates the DOM if the style element already exists.
// Conditional statements for whitelist and blacklists if user applied.
function apply(customCSSObj, whitelist, blacklist) {
console.log("[CustomCSS Injector] Applied custom CSS.");
const css = filterCustomCSSObj(customCSSObj);
const hostname = window.location.hostname;
const cssLink = document.getElementById("custom-css-injector");
if (!whitelist.hostnames || whitelist.hostnames.includes(hostname)) {
if (!blacklist.hostnames.includes(hostname)) {
if (cssLink === null) {
const cssLink = document.createElement("style");
cssLink.setAttribute("type", "text/css");
cssLink.setAttribute("id", "custom-css-injector");
cssLink.textContent = css;
document.documentElement.appendChild(cssLink);
return;
}
else {
cssLink.textContent = css;
return;
}
}
}
if (cssLink != null) {
cssLink.parentElement.removeChild(cssLink);
}
}
// Checks for site-specific or domain-specific applied CSS and returns it to apply()
function filterCustomCSSObj(customCSSObj) {
if (customCSSObj == null) {
return "";
}
const url = window.location.href;
const domain = window.location.hostname;
return customCSSObj[url]
|| customCSSObj[domain]
|| customCSSObj.css;
}
// Handles message from Popup script and returns the URL and DOMAIN name of the active tab.
browser.runtime.onMessage.addListener(request => {
return Promise.resolve({domain: window.location.hostname, url: window.location.href});
});