-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinjectionInjector.js
213 lines (180 loc) · 8 KB
/
injectionInjector.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
let projectConfiguration = null;
const KEY_STORAGE_LOCAL_APPLYING_ADJUSTMENT_STATES = "page_adjustment_states";
let localCopyApplySettings = {};
determinedBrowserAPI = typeof browser !== 'undefined' ? browser : chrome;
function getProjectConfiguration() {
return fetch(determinedBrowserAPI.runtime.getURL('projectConfiguration.json'))
.then(response => response.json())
.then(data => data);
}
getProjectConfiguration().then(projectConfiguration => { localStorage.setItem("ProjectConfiguration", JSON.stringify(projectConfiguration));});
projectConfiguration = JSON.parse(localStorage.getItem("ProjectConfiguration"));
function logWithConfigMsg(...messages){
if(projectConfiguration === null){
getProjectConfiguration().then(gotProjectConfiguration => {
projectConfiguration = JSON.stringify(gotProjectConfiguration);
for(const message of messages){
if(typeof message === "object"){
console.log("["+JSON.parse(projectConfiguration).log_header+"]: "+JSON.stringify(message));
}else{
console.log("["+JSON.parse(projectConfiguration).log_header+"]: "+message);
}
}
});
}else{
for(const message of messages){
if(typeof message === "object"){
console.log("["+projectConfiguration.log_header+"]: "+JSON.stringify(message));
}else{
console.log("["+projectConfiguration.log_header+"]: "+message);
}
}
}
}
// TODO: MOVE TO A BETTER/LESS REDUNDANT SPOT. Remove Duplicate Code
function createElementLink(sheetName) {
logWithConfigMsg("Linking document name ="+sheetName);
if(sheetName.endsWith(".css")){
const stylesheetLinkElement = document.createElement('link');
stylesheetLinkElement.rel = 'stylesheet';
stylesheetLinkElement.type = 'text/css';
stylesheetLinkElement.href = determinedBrowserAPI.runtime.getURL(sheetName);
return stylesheetLinkElement;
}else if(sheetName.endsWith(".js")){
const jsSheetLinkElement=document.createElement('script')
jsSheetLinkElement.setAttribute("type","text/javascript")
jsSheetLinkElement.setAttribute("src", determinedBrowserAPI.runtime.getURL(sheetName))
return jsSheetLinkElement;
}
// primary stylesheetLinkElement;
}
function getApplySettings(key) {
return new Promise((resolve, reject) => {
determinedBrowserAPI.storage.local.get(key, (result) => {
if (determinedBrowserAPI.runtime.lastError) {
reject(determinedBrowserAPI.runtime.lastError);
} else {
// If the key is not in storage, create it with default values
if (!result[key]) {
let defaultSettings = {};
if(key === KEY_STORAGE_LOCAL_APPLYING_ADJUSTMENT_STATES) {
defaultSettings = structuredClone(projectConfiguration.DEFAULT_CHANGE_SETTINGS);
}
result[key] = defaultSettings;
determinedBrowserAPI.storage.local.set(result, () => {
if (determinedBrowserAPI.runtime.lastError) {
reject(determinedBrowserAPI.runtime.lastError);
} else {
localCopyApplySettings = result[key];
resolve(result[key]);
}
});
} else {
localCopyApplySettings = result[key];
resolve(result[key]);
}
}
});
});
}
function applySettingsUpdate(){
logWithConfigMsg("Start of applySettingsUpdate");
// TODO: Try to fix again, KEY_STORAGE_LOCAL_APPLYING_ADJUSTMENT_STATES not converted to string for some reason
determinedBrowserAPI.storage.local.set({ "page_adjustment_states": localCopyApplySettings }); // Synchronize the changes made to localCopyApplySettings
}
determinedBrowserAPI.storage.onChanged.addListener((changes, areaName) => {
if (areaName === "local" && KEY_STORAGE_LOCAL_APPLYING_ADJUSTMENT_STATES in changes) {
for (let key in changes) {
const settings = JSON.parse(JSON.stringify(changes[key].newValue));//TODO: Make sure this is efficient{
logWithConfigMsg(`Key "${key}" in area "${areaName}" changed. New value is ${JSON.stringify(changes[key].newValue)}.`);
localCopyApplySettings = settings;
if(key===KEY_STORAGE_LOCAL_APPLYING_ADJUSTMENT_STATES){
settingsToActions(settings);
}
}
}
});
function stateApprover(){
return window.location.pathname.split('/').pop() !== "popup.html";
}
// START INJECTOR BASED SETTINGS HELPERS
function setInjectionStateHelper(state, id, filePath){
if(!stateApprover()){//Currently terminates if on popup.html, in the future more options may be available
return;
}
if(typeof filePath == "undefined"){//Make id filepath for overloading
if(typeof id == "undefined"){//If both undefined for overloading
id = state;
state = true;
}
filePath = id;
id = "exampleDemoProject_injected_CSS__"+filePath.substring((filePath.lastIndexOf("/")+1===-1 ? 0 : (filePath.lastIndexOf("/")+1)),filePath.lastIndexOf("."));
}
let element = document.getElementById(id);
if (state === true) {
// TODO: Make more efficient, right now trys removal and re-add
if(element === null) {
element = createElementLink(filePath);
element.id = id;
document.head.appendChild(element);
}
} else if (state === false) {
try{
element.parentElement.removeChild(element);
}catch(e){}
}
}
function setProperty(propertyName, value){
var root = document.querySelector(':root');//TODO: Inefficient?
if(!propertyName.startsWith("--")){
propertyName = "--".concat(propertyName);
}
root.style.setProperty(propertyName, value);
}
// END INJECTOR BASED SETTINGS HELPERS
function settingsToActions(){
getApplySettings(KEY_STORAGE_LOCAL_APPLYING_ADJUSTMENT_STATES).then((applySettings) => {
logWithConfigMsg("Settings used:");
const keys = Object.keys(applySettings);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = applySettings[keys[i]].value;
// Simple (value, location) when dealing with booleans, true adds css, false removes it by autogen ID
if(key === "BOOLEAN_VALUE_KEY") {
setInjectionStateHelper( value, "injection_parts/primary/greenH1.css");
}
/* CSS files requiring variables as properties use (variable-name-no-starting-dashes, value-to-be-set-to)
And then just (location) */
else if(key === "NUMBER_VALUE_KEY"){
setProperty("content-width", value+"%");//TODO: Autogen variables
setInjectionStateHelper( "injection_parts/primary/content_width.css");
}else if(key === "NUMBER_WITH_ALL_OPTIONS_KEY"){
setProperty("content-border-radius", value+"em");
setInjectionStateHelper( "injection_parts/primary/border_radius_em.css");
}
}
}).catch((error) => {
console.error(error);
});
}
// Initial setup/initial receive
console.log("Running initial applySettings...");
settingsToActions();
setTimeout(function(){
console.log("Executed after 1 second");
settingsToActions();
}, 1000);
// SPECIFICS TO YOUTUBE.COM
/*
* SPECIFIC TO YOUTUBE - listens for all video changes and re-applies
* */
// const videoObserver = new MutationObserver((mutations) => {
// mutations.forEach((mutation) => {
// if (mutation.type === 'attributes' && mutation.attributeName === 'src') {
//
// }
// });
// });
//
// // Observe changes
// videoObserver.observe(document.querySelector("video"), { attributes: true, attributeFilter: ['src'] });