-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
378 lines (335 loc) · 9.86 KB
/
utils.js
File metadata and controls
378 lines (335 loc) · 9.86 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
// Shared utilities for AdBlock Shield extension
// Known ad network domains (expanded 2025 list)
const AD_NETWORKS = [
'doubleclick.net',
'googlesyndication.com',
'googleadservices.com',
'adservice.google.com',
'advertising.com',
'adnxs.com',
'adsystem.com',
'criteo.com',
'outbrain.com',
'taboola.com',
'serving-sys.com',
'pubmatic.com',
'rubiconproject.com',
'openx.net',
'casalemedia.com',
'advertising.yahoo.com',
'ads.yahoo.com',
'popads.net',
'popcash.net',
'adcash.com',
'propellerads.com',
'mgid.com',
'revcontent.com',
'zedo.com',
'quantserve.com',
'ad.doubleclick.net',
'adserver.com',
'adsrvr.org',
'bidswitch.net',
'media.net',
'inmobi.com',
'smaato.net',
'applovin.com',
'unity3d.com'
];
// Ad-related keywords for class/id detection
const AD_KEYWORDS = [
'ad-overlay',
'ad_overlay',
'adoverlay',
'popup-ad',
'popupad',
'ad-modal',
'advertisement',
'sponsored-content',
'ad-container',
'interstitial',
'lightbox-ad',
'overlay-ad',
'modal-ad',
'fullscreen-ad',
'takeover',
'ad-blocker-message',
'anti-adblock'
];
// Tracking parameter patterns (expanded 2025 list)
const TRACKING_PARAMS = [
'utm_',
'fbclid',
'gclid',
'msclkid',
'mc_cid',
'mc_eid',
'_ga',
'yclid',
'ttclid', // TikTok
'igshid', // Instagram
'twclid', // Twitter/X
'li_fat_id', // LinkedIn
'gbraid', // Google Ads
'wbraid', // Google Ads
'spm', // AliExpress/Taobao
'scm' // Social commerce
];
/**
* Check if a domain is in the whitelist
* @param {string} domain - Domain to check
* @returns {Promise<boolean>}
*/
async function isWhitelisted(domain) {
try {
const result = await chrome.storage.sync.get(['whitelist']);
const whitelist = result.whitelist || [];
return whitelist.includes(domain);
} catch (error) {
console.error('Error checking whitelist:', error);
return false;
}
}
/**
* Get current domain from URL
* @param {string} url - Full URL
* @returns {string} Domain name
*/
function getDomain(url) {
try {
const urlObj = new URL(url);
return urlObj.hostname;
} catch (error) {
return '';
}
}
/**
* Check if URL contains tracking parameters
* @param {string} url - URL to check
* @returns {boolean}
*/
function hasTrackingParams(url) {
return TRACKING_PARAMS.some(param => url.includes(param));
}
/**
* Check if URL is from known ad network
* @param {string} url - URL to check
* @returns {boolean}
*/
function isAdNetwork(url) {
try {
const domain = getDomain(url);
return AD_NETWORKS.some(adDomain => domain.includes(adDomain));
} catch (error) {
return false;
}
}
/**
* Check if element has ad-related class or ID
* @param {HTMLElement} element - Element to check
* @returns {boolean}
*/
function hasAdKeywords(element) {
const className = element.className || '';
const id = element.id || '';
const combined = (className + ' ' + id).toLowerCase();
return AD_KEYWORDS.some(keyword => combined.includes(keyword));
}
/**
* Calculate overlay score to determine if element is an ad overlay
* Uses heuristic scoring: score > 50 = likely ad overlay (lowered from 60)
* @param {HTMLElement} element - Element to analyze
* @returns {number} Score from 0-100
*/
function calculateOverlayScore(element) {
let score = 0;
try {
const computedStyle = window.getComputedStyle(element);
const rect = element.getBoundingClientRect();
// Check z-index (high z-index indicates overlay)
const zIndex = parseInt(computedStyle.zIndex) || 0;
if (zIndex > 999) score += 30;
else if (zIndex > 500) score += 15;
else if (zIndex > 100) score += 5;
// Check position (fixed/absolute suggests overlay)
const position = computedStyle.position;
if (position === 'fixed') score += 20;
else if (position === 'absolute') score += 10;
// Check dimensions (full-screen indicates overlay)
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const widthRatio = rect.width / viewportWidth;
const heightRatio = rect.height / viewportHeight;
if (widthRatio > 0.8 && heightRatio > 0.8) score += 25;
else if (widthRatio > 0.6 && heightRatio > 0.6) score += 15;
else if (widthRatio > 0.4 && heightRatio > 0.4) score += 8;
// Check for ad-related keywords in class/id
if (hasAdKeywords(element)) score += 40;
// Check for iframe with ad network source
const iframes = element.querySelectorAll('iframe');
for (const iframe of iframes) {
if (iframe.src && isAdNetwork(iframe.src)) {
score += 50;
break;
}
}
// Check for backdrop/modal characteristics
const backgroundColor = computedStyle.backgroundColor;
const opacity = parseFloat(computedStyle.opacity) || 1;
if (backgroundColor.includes('rgba') && opacity < 0.9) {
score += 10;
}
// Check pointer-events (overlays often have pointer-events: auto)
const pointerEvents = computedStyle.pointerEvents;
if (pointerEvents === 'auto' && zIndex > 100) {
score += 10;
}
// Check if body scroll is disabled (common overlay behavior)
const bodyOverflow = document.body.style.overflow;
const htmlOverflow = document.documentElement.style.overflow;
if (bodyOverflow === 'hidden' || htmlOverflow === 'hidden') {
score += 15;
}
// Check for display property transitions (ads often fade in)
const display = computedStyle.display;
const visibility = computedStyle.visibility;
if (display === 'block' && visibility === 'visible' && position === 'fixed') {
score += 5;
}
// Check if element is covering viewport exactly (common ad pattern)
const top = parseInt(computedStyle.top) || rect.top;
const left = parseInt(computedStyle.left) || rect.left;
if (Math.abs(top) < 10 && Math.abs(left) < 10 && widthRatio > 0.9) {
score += 10;
}
} catch (error) {
console.error('Error calculating overlay score:', error);
}
return score;
}
/**
* Check if link is suspicious and should be blocked
* @param {HTMLAnchorElement} link - Link element to check
* @returns {boolean}
*/
function isSuspiciousLink(link) {
try {
const href = link.href || '';
const target = link.target || '';
const onclick = link.getAttribute('onclick') || '';
const rel = link.rel || '';
// Check if external link
const currentDomain = window.location.hostname;
const linkDomain = getDomain(href);
const isExternal = linkDomain && linkDomain !== currentDomain;
// Score-based detection (threshold lowered to 40 from 50)
let suspicionScore = 0;
// External link with target="_blank"
if (isExternal && target === '_blank') suspicionScore += 20;
// Has onclick handler
if (onclick.includes('window.open')) suspicionScore += 40;
if (onclick.includes('location.href')) suspicionScore += 25;
// Known ad network
if (isAdNetwork(href)) suspicionScore += 50;
// Has tracking parameters
if (hasTrackingParams(href)) suspicionScore += 15;
// Short or obfuscated URLs
if (href.length < 20 && isExternal) suspicionScore += 10;
// Has ad-related keywords in URL
const lowerHref = href.toLowerCase();
if (AD_KEYWORDS.some(keyword => lowerHref.includes(keyword))) {
suspicionScore += 30;
}
// Suspicious link text (common ad patterns)
const linkText = (link.textContent || '').toLowerCase();
if (linkText.includes('click here') || linkText.includes('download now') ||
linkText.includes('free') || linkText.includes('winner')) {
suspicionScore += 10;
}
// Missing rel="noopener" or "noreferrer" on external _blank links (suspicious)
if (isExternal && target === '_blank' && !rel.includes('noopener') && !rel.includes('noreferrer')) {
suspicionScore += 10;
}
// Very long URLs (often redirect chains)
if (href.length > 200) suspicionScore += 15;
return suspicionScore > 40;
} catch (error) {
return false;
}
}
/**
* Get extension settings from storage
* @returns {Promise<Object>}
*/
async function getSettings() {
try {
const result = await chrome.storage.sync.get(['enabled', 'whitelist', 'stats']);
return {
enabled: result.enabled !== false, // Default to true
whitelist: result.whitelist || [],
stats: result.stats || {
overlaysBlocked: 0,
popupsBlocked: 0,
redirectsBlocked: 0
}
};
} catch (error) {
console.error('Error getting settings:', error);
return {
enabled: true,
whitelist: [],
stats: { overlaysBlocked: 0, popupsBlocked: 0, redirectsBlocked: 0 }
};
}
}
/**
* Update statistics
* @param {string} type - Type of block ('overlay', 'popup', 'redirect')
* @param {number} count - Number to increment by
*/
async function updateStats(type, count = 1) {
try {
const settings = await getSettings();
const stats = settings.stats;
switch (type) {
case 'overlay':
stats.overlaysBlocked += count;
break;
case 'popup':
stats.popupsBlocked += count;
break;
case 'redirect':
stats.redirectsBlocked += count;
break;
}
await chrome.storage.sync.set({ stats });
// Notify background script to update badge
if (typeof chrome !== 'undefined' && chrome.runtime) {
chrome.runtime.sendMessage({
action: 'updateBadge',
stats: stats
}).catch(() => {
// Ignore errors if background script is not ready
});
}
} catch (error) {
console.error('Error updating stats:', error);
}
}
// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
isWhitelisted,
getDomain,
hasTrackingParams,
isAdNetwork,
hasAdKeywords,
calculateOverlayScore,
isSuspiciousLink,
getSettings,
updateStats,
AD_NETWORKS,
AD_KEYWORDS,
TRACKING_PARAMS
};
}