-
Notifications
You must be signed in to change notification settings - Fork 30
/
prevent-element-src-loading.js
244 lines (218 loc) · 8.1 KB
/
prevent-element-src-loading.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
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
import {
hit,
toRegExp,
safeGetDescriptor,
noopFunc,
} from '../helpers';
/* eslint-disable max-len, consistent-return */
/**
* @scriptlet prevent-element-src-loading
*
* @description
* Prevents target element source loading without triggering 'onerror' listeners and not breaking 'onload' ones.
*
* ### Syntax
*
* ```text
* example.org#%#//scriptlet('prevent-element-src-loading', tagName, match)
* ```
*
* - `tagName` — required, case-insensitive target element tagName
* which `src` property resource loading will be silently prevented; possible values:
* - `script`
* - `img`
* - `iframe`
* - `link`
* - `match` — required, string or regular expression for matching the element's URL;
*
* ### Examples
*
* 1. Prevent script source loading
*
* ```adblock
* example.org#%#//scriptlet('prevent-element-src-loading', 'script' ,'adsbygoogle')
* ```
*
* @added v1.6.2.
*/
/* eslint-enable max-len */
export function preventElementSrcLoading(source, tagName, match) {
// do nothing if browser does not support Proxy or Reflect
if (typeof Proxy === 'undefined' || typeof Reflect === 'undefined') {
return;
}
const srcMockData = {
// "KCk9Pnt9" = "()=>{}"
script: 'data:text/javascript;base64,KCk9Pnt9',
// Empty 1x1 image
img: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
// Empty h1 tag
iframe: 'data:text/html;base64, PGRpdj48L2Rpdj4=',
// Empty data
link: 'data:text/plain;base64,',
};
let instance;
if (tagName === 'script') {
instance = HTMLScriptElement;
} else if (tagName === 'img') {
instance = HTMLImageElement;
} else if (tagName === 'iframe') {
instance = HTMLIFrameElement;
} else if (tagName === 'link') {
instance = HTMLLinkElement;
} else {
return;
}
// For websites that use Trusted Types
// https://w3c.github.io/webappsec-trusted-types/dist/spec/
const hasTrustedTypes = window.trustedTypes && typeof window.trustedTypes.createPolicy === 'function';
let policy;
if (hasTrustedTypes) {
// The name for the trusted-types policy should only be 'AGPolicy',because corelibs can
// allow our policy if the server has restricted the creation of a trusted-types policy with
// the directive 'Content-Security-Policy: trusted-types <policyName>;`.
// If such a header is presented in the server response, corelibs adds permission to create
// the 'AGPolicy' policy with the 'allow-duplicates' option to prevent errors.
// See AG-18204 for details.
policy = window.trustedTypes.createPolicy('AGPolicy', {
createScriptURL: (arg) => arg,
});
}
const SOURCE_PROPERTY_NAME = tagName === 'link' ? 'href' : 'src';
const ONERROR_PROPERTY_NAME = 'onerror';
const searchRegexp = toRegExp(match);
// This will be needed to silent error events on matched element,
// as url wont be available
const setMatchedAttribute = (elem) => elem.setAttribute(source.name, 'matched');
const setAttributeWrapper = (target, thisArg, args) => {
// Check if arguments are present
if (!args[0] || !args[1]) {
return Reflect.apply(target, thisArg, args);
}
const nodeName = thisArg.nodeName.toLowerCase();
const attrName = args[0].toLowerCase();
const attrValue = args[1];
const isMatched = attrName === SOURCE_PROPERTY_NAME
&& tagName.toLowerCase() === nodeName
&& srcMockData[nodeName]
&& searchRegexp.test(attrValue);
if (!isMatched) {
return Reflect.apply(target, thisArg, args);
}
hit(source);
setMatchedAttribute(thisArg);
// Forward the URI that corresponds with element's MIME type
return Reflect.apply(target, thisArg, [attrName, srcMockData[nodeName]]);
};
const setAttributeHandler = {
apply: setAttributeWrapper,
};
// eslint-disable-next-line max-len
instance.prototype.setAttribute = new Proxy(Element.prototype.setAttribute, setAttributeHandler);
const origSrcDescriptor = safeGetDescriptor(instance.prototype, SOURCE_PROPERTY_NAME);
if (!origSrcDescriptor) {
return;
}
Object.defineProperty(instance.prototype, SOURCE_PROPERTY_NAME, {
enumerable: true,
configurable: true,
get() {
return origSrcDescriptor.get.call(this);
},
set(urlValue) {
const nodeName = this.nodeName.toLowerCase();
const isMatched = tagName.toLowerCase() === nodeName
&& srcMockData[nodeName]
&& searchRegexp.test(urlValue);
if (!isMatched) {
origSrcDescriptor.set.call(this, urlValue);
// eslint-disable-next-line no-setter-return
return true;
}
// eslint-disable-next-line no-undef
if (policy && urlValue instanceof TrustedScriptURL) {
const trustedSrc = policy.createScriptURL(urlValue);
origSrcDescriptor.set.call(this, trustedSrc);
hit(source);
return;
}
setMatchedAttribute(this);
origSrcDescriptor.set.call(this, srcMockData[nodeName]);
hit(source);
},
});
// https://github.com/AdguardTeam/Scriptlets/issues/228
// Prevent error event being triggered by other sources
const origOnerrorDescriptor = safeGetDescriptor(HTMLElement.prototype, ONERROR_PROPERTY_NAME);
if (!origOnerrorDescriptor) {
return;
}
Object.defineProperty(HTMLElement.prototype, ONERROR_PROPERTY_NAME, {
enumerable: true,
configurable: true,
get() {
return origOnerrorDescriptor.get.call(this);
},
set(cb) {
const isMatched = this.getAttribute(source.name) === 'matched';
if (!isMatched) {
origOnerrorDescriptor.set.call(this, cb);
// eslint-disable-next-line no-setter-return
return true;
}
origOnerrorDescriptor.set.call(this, noopFunc);
// eslint-disable-next-line no-setter-return
return true;
},
});
const addEventListenerWrapper = (target, thisArg, args) => {
// Check if arguments are present
if (!args[0] || !args[1] || !thisArg) {
return Reflect.apply(target, thisArg, args);
}
const eventName = args[0];
const isMatched = typeof thisArg.getAttribute === 'function'
&& thisArg.getAttribute(source.name) === 'matched'
&& eventName === 'error';
if (isMatched) {
return Reflect.apply(target, thisArg, [eventName, noopFunc]);
}
return Reflect.apply(target, thisArg, args);
};
const addEventListenerHandler = {
apply: addEventListenerWrapper,
};
// eslint-disable-next-line max-len
EventTarget.prototype.addEventListener = new Proxy(EventTarget.prototype.addEventListener, addEventListenerHandler);
const preventInlineOnerror = (tagName, src) => {
window.addEventListener('error', (event) => {
if (
!event.target
|| !event.target.nodeName
|| event.target.nodeName.toLowerCase() !== tagName
|| !event.target.src
|| !src.test(event.target.src)
) {
return;
}
hit(source);
if (typeof event.target.onload === 'function') {
event.target.onerror = event.target.onload;
return;
}
event.target.onerror = noopFunc;
}, true);
};
preventInlineOnerror(tagName, searchRegexp);
}
export const preventElementSrcLoadingNames = [
'prevent-element-src-loading',
];
// eslint-disable-next-line prefer-destructuring
preventElementSrcLoading.primaryName = preventElementSrcLoadingNames[0];
preventElementSrcLoading.injections = [
hit,
toRegExp,
safeGetDescriptor,
noopFunc,
];