forked from gorhill/httpswitchboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentscript-end.js
More file actions
563 lines (490 loc) · 17.7 KB
/
contentscript-end.js
File metadata and controls
563 lines (490 loc) · 17.7 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/*******************************************************************************
httpswitchboard - a Chromium browser extension to black/white list requests.
Copyright (C) 2013 Raymond Hill
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/httpswitchboard
*/
/* jshint multistr: true */
/* global chrome */
// Injected into content pages
/******************************************************************************/
/******************************************************************************/
// https://github.com/gorhill/httpswitchboard/issues/345
var messaging = (function(name){
var port = null;
var dangling = false;
var requestId = 1;
var requestIdToCallbackMap = {};
var listenCallback = null;
var onPortMessage = function(details) {
if ( typeof details.id !== 'number' ) {
return;
}
// Announcement?
if ( details.id < 0 ) {
if ( listenCallback ) {
listenCallback(details.msg);
}
return;
}
var callback = requestIdToCallbackMap[details.id];
if ( !callback ) {
return;
}
callback(details.msg);
delete requestIdToCallbackMap[details.id];
checkDisconnect();
};
var start = function(name) {
port = chrome.runtime.connect({
name: name +
'/' +
String.fromCharCode(
Math.random() * 0x7FFF | 0,
Math.random() * 0x7FFF | 0,
Math.random() * 0x7FFF | 0,
Math.random() * 0x7FFF | 0
)
});
port.onMessage.addListener(onPortMessage);
};
if ( typeof name === 'string' && name.length > 0 ) {
start(name);
}
var stop = function() {
listenCallback = null;
dangling = true;
checkDisconnect();
};
var ask = function(msg, callback) {
if ( !callback ) {
tell(msg);
return;
}
var id = requestId++;
port.postMessage({ id: id, msg: msg });
requestIdToCallbackMap[id] = callback;
};
var tell = function(msg) {
port.postMessage({ id: 0, msg: msg });
};
var listen = function(callback) {
listenCallback = callback;
};
var checkDisconnect = function() {
if ( !dangling ) {
return;
}
if ( Object.keys(requestIdToCallbackMap).length ) {
return;
}
port.disconnect();
port = null;
};
return {
start: start,
stop: stop,
ask: ask,
tell: tell,
listen: listen
};
})('contentscript-end.js');
/******************************************************************************/
/******************************************************************************/
// This is to be executed only once: putting this code in its own closure
// means the code will be flushed from memory once executed.
(function() {
/******************************************************************************/
/*------------[ Unrendered Noscript (because CSP) Workaround ]----------------*/
var checkScriptBlacklistedHandler = function(response) {
if ( !response.scriptBlacklisted ) {
return;
}
var scripts = document.querySelectorAll('noscript');
var i = scripts.length;
var realNoscript, fakeNoscript;
while ( i-- ) {
realNoscript = scripts[i];
fakeNoscript = document.createElement('div');
fakeNoscript.innerHTML = '<!-- HTTP Switchboard NOSCRIPT tag replacement: see <https://github.com/gorhill/httpswitchboard/issues/177> -->\n' + realNoscript.textContent;
realNoscript.parentNode.replaceChild(fakeNoscript, realNoscript);
}
};
messaging.ask({
what: 'checkScriptBlacklisted',
url: window.location.href
},
checkScriptBlacklistedHandler
);
/******************************************************************************/
var localStorageHandler = function(mustRemove) {
if ( mustRemove ) {
window.localStorage.clear();
// console.debug('HTTP Switchboard > found and removed non-empty localStorage');
}
};
// Check with extension whether local storage must be emptied
// rhill 2014-03-28: we need an exception handler in case 3rd-party access
// to site data is disabled.
// https://github.com/gorhill/httpswitchboard/issues/215
try {
if ( window.localStorage && window.localStorage.length ) {
messaging.ask({
what: 'contentScriptHasLocalStorage',
url: window.location.href
},
localStorageHandler
);
}
// TODO: indexedDB
if ( window.indexedDB && !!window.indexedDB.webkitGetDatabaseNames ) {
// var db = window.indexedDB.webkitGetDatabaseNames().onsuccess = function(sender) {
// console.debug('webkitGetDatabaseNames(): result=%o', sender.target.result);
// };
}
// TODO: Web SQL
if ( window.openDatabase ) {
// Sad:
// "There is no way to enumerate or delete the databases available for an origin from this API."
// Ref.: http://www.w3.org/TR/webdatabase/#databases
}
}
catch (e) {
}
/******************************************************************************/
})();
/******************************************************************************/
/******************************************************************************/
(function() {
/******************************************************************************/
// ABP cosmetic filters
var cosmeticFiltering = (function() {
var queriedSelectors = {};
var injectedSelectors = {};
var classSelectors = null;
var idSelectors = null;
var domLoaded = function() {
// https://github.com/gorhill/uBlock/issues/14
// Treat any existing domain-specific exception selectors as if they had
// been injected already.
var style = document.getElementById('uBlock1ae7a5f130fc79b4fdb8a4272d9426b5');
var exceptions = style && style.getAttribute('uBlock1ae7a5f130fc79b4fdb8a4272d9426b5');
if ( exceptions ) {
exceptions = decodeURIComponent(exceptions).split('\n');
var i = exceptions.length;
while ( i-- ) {
injectedSelectors[exceptions[i]] = true;
}
}
selectorsFromNodeList(document.querySelectorAll('*[class],*[id]'));
retrieveGenericSelectors();
};
var retrieveGenericSelectors = function() {
var selectors = classSelectors !== null ? Object.keys(classSelectors) : [];
if ( idSelectors !== null ) {
selectors = selectors.concat(idSelectors);
}
if ( selectors.length > 0 ) {
//console.log('HTTPSB> ABP cosmetic filters: retrieving CSS rules using %d selectors', selectors.length);
messaging.ask({
what: 'retrieveGenericCosmeticSelectors',
pageURL: window.location.href,
selectors: selectors
},
retrieveHandler
);
}
idSelectors = null;
classSelectors = null;
};
var retrieveHandler = function(selectors) {
if ( !selectors ) {
return;
}
var styleText = [];
filterUnfiltered(selectors.hideUnfiltered, selectors.hide);
reduce(selectors.hide, injectedSelectors);
if ( selectors.hide.length ) {
var hideStyleText = '{{hideSelectors}} {display:none !important;}'
.replace('{{hideSelectors}}', selectors.hide.join(','));
styleText.push(hideStyleText);
applyCSS(selectors.hide, 'display', 'none');
//console.debug('HTTPSB> generic cosmetic filters: injecting %d CSS rules:', selectors.hide.length, hideStyleText);
}
filterUnfiltered(selectors.donthideUnfiltered, selectors.donthide);
reduce(selectors.donthide, injectedSelectors);
if ( selectors.donthide.length ) {
var dontHideStyleText = '{{donthideSelectors}} {display:initial !important;}'
.replace('{{donthideSelectors}}', selectors.donthide.join(','));
styleText.push(dontHideStyleText);
applyCSS(selectors.donthide, 'display', 'initial');
//console.debug('HTTPSB> generic cosmetic filters: injecting %d CSS rules:', selectors.donthide.length, dontHideStyleText);
}
if ( styleText.length > 0 ) {
var style = document.createElement('style');
style.appendChild(document.createTextNode(styleText.join('\n')));
var parent = document.body || document.documentElement;
if ( parent ) {
parent.appendChild(style);
}
}
};
var applyCSS = function(selectors, prop, value) {
if ( document.body === null ) {
return;
}
var elems = document.querySelectorAll(selectors);
var i = elems.length;
while ( i-- ) {
elems[i].style[prop] = value;
}
};
var filterUnfiltered = function(inSelectors, outSelectors) {
var i = inSelectors.length;
var selector;
while ( i-- ) {
selector = inSelectors[i];
if ( injectedSelectors[selector] ) {
continue;
}
if ( document.querySelector(selector) !== null ) {
outSelectors.push(selector);
}
}
};
var reduce = function(selectors, dict) {
var i = selectors.length, selector, end;
while ( i-- ) {
selector = selectors[i];
if ( !dict[selector] ) {
if ( end !== undefined ) {
selectors.splice(i+1, end-i);
end = undefined;
}
dict[selector] = true;
} else if ( end === undefined ) {
end = i;
}
}
if ( end !== undefined ) {
selectors.splice(0, end+1);
}
};
var selectorsFromNodeList = function(nodes) {
if ( !nodes || !nodes.length ) {
return;
}
if ( idSelectors === null ) {
idSelectors = [];
}
if ( classSelectors === null ) {
classSelectors = {};
}
var qq = queriedSelectors;
var cc = classSelectors;
var ii = idSelectors;
var node, v, classNames, j;
var i = nodes.length;
while ( i-- ) {
node = nodes[i];
if ( node.nodeType !== 1 ) {
continue;
}
// id
v = nodes[i].id;
// https://github.com/gorhill/httpswitchboard/issues/397
// `id` can be something else than a string
if ( typeof v !== 'string' ) {
v = '';
} else {
v = v.trim();
}
if ( v !== '' ) {
v = '#' + v;
if ( !qq[v] ) {
ii.push(v);
qq[v] = true;
}
}
// class
v = nodes[i].className;
// it could be an SVGAnimatedString...
if ( typeof v !== 'string' ) { continue; }
v = v.trim();
if ( v === '' ) { continue; }
// one class
if ( v.indexOf(' ') < 0 ) {
v = '.' + v;
if ( qq[v] ) { continue; }
cc[v] = true;
qq[v] = true;
continue;
}
// many classes
classNames = v.trim().split(/\s+/);
j = classNames.length;
while ( j-- ) {
v = classNames[j];
if ( v === '' ) { continue; }
v = '.' + v;
if ( qq[v] ) { continue; }
cc[v] = true;
qq[v] = true;
}
}
};
var processNodeLists = function(nodeLists) {
var i = nodeLists.length;
var nodeList, j, node;
while ( i-- ) {
nodeList = nodeLists[i];
selectorsFromNodeList(nodeList);
j = nodeList.length;
while ( j-- ) {
node = nodeList[j];
if ( node.querySelectorAll ) {
selectorsFromNodeList(node.querySelectorAll('*[id],*[class]'));
}
}
}
retrieveGenericSelectors();
};
domLoaded();
return {
processNodeLists: processNodeLists
};
})();
/******************************************************************************/
var nodesAddedHandler = function(nodeList, summary) {
var i = 0;
var node, src, text;
while ( node = nodeList.item(i++) ) {
if ( !node.tagName ) {
continue;
}
switch ( node.tagName.toUpperCase() ) {
case 'SCRIPT':
// https://github.com/gorhill/httpswitchboard/issues/252
// Do not count HTTPSB's own script tags, they are not required
// to "unbreak" a web page
if ( node.id && node.id.indexOf('httpsb-') === 0 ) {
break;
}
text = node.textContent.trim();
if ( text !== '' ) {
summary.scriptSources['{inline_script}'] = true;
summary.mustReport = true;
}
src = (node.src || '').trim();
if ( src !== '' ) {
summary.scriptSources[src] = true;
summary.mustReport = true;
}
break;
case 'A':
if ( node.href.indexOf('javascript:') === 0 ) {
summary.scriptSources['{inline_script}'] = true;
summary.mustReport = true;
}
break;
case 'OBJECT':
src = (node.data || '').trim();
if ( src !== '' ) {
summary.pluginSources[src] = true;
summary.mustReport = true;
}
break;
case 'EMBED':
src = (node.src || '').trim();
if ( src !== '' ) {
summary.pluginSources[src] = true;
summary.mustReport = true;
}
break;
}
}
};
/******************************************************************************/
var nodeListsAddedHandler = function(nodeLists) {
var summary = {
what: 'contentScriptSummary',
locationURL: window.location.href,
scriptSources: {}, // to avoid duplicates
pluginSources: {}, // to avoid duplicates
mustReport: false
};
var i = nodeLists.length;
while ( i-- ) {
nodesAddedHandler(nodeLists[i], summary);
}
if ( summary.mustReport ) {
messaging.tell(summary);
}
};
/******************************************************************************/
// rhill 2013-11-09: Weird... This code is executed from HTTP Switchboard
// context first time extension is launched. Avoid this.
// TODO: Investigate if this was a fluke or if it can really happen.
// I suspect this could only happen when I was using chrome.tabs.executeScript(),
// because now a delarative content script is used, along with "http{s}" URL
// pattern matching.
// console.debug('HTTPSB> window.location.href = "%s"', window.location.href);
if ( /^https?:\/\/./.test(window.location.href) === false ) {
console.debug("Huh?");
return;
}
/******************************************************************************/
(function() {
var summary = {
what: 'contentScriptSummary',
locationURL: window.location.href,
scriptSources: {}, // to avoid duplicates
pluginSources: {}, // to avoid duplicates
mustReport: true
};
// https://github.com/gorhill/httpswitchboard/issues/25
// &
// Looks for inline javascript also in at least one a[href] element.
// https://github.com/gorhill/httpswitchboard/issues/131
nodesAddedHandler(document.querySelectorAll('script, a[href^="javascript:"], object, embed'), summary);
//console.debug('HTTPSB> firstObservationHandler(): found %d script tags in "%s"', Object.keys(summary.scriptSources).length, window.location.href);
messaging.tell(summary);
})();
/******************************************************************************/
// Observe changes in the DOM
var mutationObservedHandler = function(mutations) {
var i = mutations.length;
var nodeLists = [], nodeList;
while ( i-- ) {
nodeList = mutations[i].addedNodes;
if ( nodeList && nodeList.length ) {
nodeLists.push(nodeList);
}
}
if ( nodeLists.length ) {
cosmeticFiltering.processNodeLists(nodeLists);
nodeListsAddedHandler(nodeLists);
}
};
// This fixes http://acid3.acidtests.org/
if ( document.body ) {
// https://github.com/gorhill/httpswitchboard/issues/176
var observer = new MutationObserver(mutationObservedHandler);
observer.observe(document.body, {
attributes: false,
childList: true,
characterData: false,
subtree: true
});
}
/******************************************************************************/
})();