-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
231 lines (205 loc) · 6.37 KB
/
background.js
File metadata and controls
231 lines (205 loc) · 6.37 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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
'use strict';
/*
* Basic settings for modern browsers
*
* Programming Note: Just tweak these constants for each browser.
* It should work fine across Edge, Chrome and Firefox without any
* further modifications.
*/
const BROWSER = 'edge';
const SERVER_NAME = 'com.clear_code.repost_confirmation_canceler';
const ALARM_MINUTES = 0.5;
/*
* RepostConfirmationCanceler's matching function
*
* 1. `?` represents a single character.
* 2. `*` represents an arbitrary substring.
*
* >>> wildcmp("http?://*.example.com/*", "https://www.example.com/")
* true
*/
function wildcmp(wild, string) {
if(!wild || !string) {
return false;
}
const pattern = wildcardToRegexp(wild);
const regex = new RegExp(`^${pattern}$`, "i");
return regex.test(string);
};
function wildcardToRegexp(source) {
// https://stackoverflow.com/questions/6300183/sanitize-string-of-regex-characters-before-regexp-build
const sanitized = source.replace(/[#-.]|[[-^]|[?|{}]/g, "\\$&");
const wildcardAccepted = sanitized.replace(/\\\*/g, ".*").replace(/\\\?/g, ".");
return wildcardAccepted;
}
/*
* Observe WebRequests with config fetched from RepostConfirmationCanceler.
*
* A typical configuration looks like this:
*
* {
* Sections: [
* {Name:"edge", Patterns:["*://example.com/*"], Excludes:[]},
* ...
* ]
* }
*/
const RepostConfirmationCanceler = {
cached: null,
init() {
this.cached = null;
this.ensureLoadedAndConfigured();
console.log('Running RepostConfirmationCanceler');
},
async ensureLoadedAndConfigured() {
return this._promisedLoadedAndConfigured = this._promisedLoadedAndConfigured || Promise.all([
!this.cached && this.configure()
]);
},
_promisedLoadedAndConfigured: null,
async configure() {
const query = new String('C ' + BROWSER);
const resp = await chrome.runtime.sendNativeMessage(SERVER_NAME, query);
if (chrome.runtime.lastError || !resp) {
console.log('Cannot fetch config', query, JSON.stringify(chrome.runtime.lastError));
return;
}
const isStartup = (this.cached == null);
this.cached = resp.config;
this.cached.NamedSections = Object.fromEntries(resp.config.Sections.map(section => [section.Name.toLowerCase(), section]));
console.log('Fetch config', JSON.stringify(this.cached));
if (isStartup) {
this.handleStartup();
}
},
/*
* Request monitoring to Native Messaging Hosts.
* * Request Example: "Q edge".
*/
startMonitoring() {
const query = new String('Q ' + BROWSER);
console.log(`Cenceler: Send start monitoring message: ${query}`);
chrome.runtime.sendNativeMessage(SERVER_NAME, query);
},
match(section, url) {
for (let pattern of (section.Excludes || [])) {
if (Array.isArray(pattern)) {
pattern = pattern[0];
}
if (wildcmp(pattern, url)) {
console.log(`* Match Exclude ${section.Name} [${pattern}]`);
return false;
}
}
for (let pattern of (section.Patterns || [])) {
if (Array.isArray(pattern)) {
pattern = pattern[0];
}
if (wildcmp(pattern, url)) {
console.log(`* Match ${section.Name} [${pattern}]`);
return true;
}
}
return false;
},
handleURL(config, url, callbackWhenMatch){
if (!url) {
console.log(`* Empty URL found`);
return false;
}
if (!/^https?:/.test(url)) {
console.log(`* Ignore non-HTTP/HTTPS URL ${url}`);
return false;
}
const urlToMatch = url;
console.log(`* Lookup sections for ${urlToMatch}`);
for (const section of config.Sections) {
if (section.Name.toLowerCase() !== "targets")
{
continue;
}
console.log(`handleURL: check for section ${section.Name} (${JSON.stringify(section)})`);
if (this.match(section, urlToMatch)) {
console.log(` => matched`);
callbackWhenMatch();
return true;
}
else {
console.log(` => unmatched`);
continue;
}
}
return false;
},
handleAllTabs() {
const config = this.cached;
console.log(`handleAllTabs`);
chrome.tabs.query({ }).then(tabs => {
for (const tab of tabs) {
const url = tab.url ?? tab.pendingUrl;
console.log(`handleAllTabs ${url} (tab=${tab.id})`);
if(this.handleURL(config, url, this.startMonitoring)){
break;
}
};
});
},
handleStartup() {
this.handleAllTabs();
},
async onTabUpdated(tabId, info, tab) {
await this.ensureLoadedAndConfigured();
const config = this.cached;
const url = tab.pendingUrl || tab.url;
this.handleURL(config, url, this.startMonitoring);
},
onNavigationCommitted(details) {
const url = details.url;
console.log(`onNavigationCommitted: ${url}`);
const config = this.cached;
this.handleURL(config, url, this.startMonitoring);
},
onErrorOccurred(details) {
console.log('onErrorOccurred:', details);
if (details.error === 'net::ERR_CACHE_MISS') {
const url = details.url;
const tabId = details.tabId;
const config = this.cached;
if (config.CloseErrCacheMissPage) {
this.handleURL(config, url, () => {
this.closeTab(tabId);
});
}
}
},
closeTab(tabId) {
if (tabId !== -1) {
console.log("Closing tab:", tabId);
chrome.tabs.remove(tabId, () => {
if (chrome.runtime.lastError) {
console.log("Error while closing tab:", chrome.runtime.lastError.message)
} else {
console.log("Tab closed");
}
});
}
}
};
/* Refresh config for every N minute */
console.log('Poll config for every', ALARM_MINUTES , 'minutes');
chrome.alarms.create('poll-config', {'periodInMinutes': ALARM_MINUTES});
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'poll-config') {
RepostConfirmationCanceler.configure();
RepostConfirmationCanceler.handleAllTabs();
//handleURL for all url in tabs.
}
});
chrome.webRequest.onErrorOccurred.addListener(
RepostConfirmationCanceler.onErrorOccurred.bind(RepostConfirmationCanceler),
{urls: ["<all_urls>"]}
);
/* Tab book-keeping for intelligent tab handlings */
chrome.tabs.onUpdated.addListener(RepostConfirmationCanceler.onTabUpdated.bind(RepostConfirmationCanceler));
chrome.webNavigation.onCommitted.addListener(RepostConfirmationCanceler.onNavigationCommitted.bind(RepostConfirmationCanceler));
RepostConfirmationCanceler.init();