-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathyoutube-ad-detection.js
More file actions
765 lines (662 loc) · 28.1 KB
/
youtube-ad-detection.js
File metadata and controls
765 lines (662 loc) · 28.1 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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
import { isVisible, toRegExpArray } from '../utils/detection-utils.js';
/**
* @typedef {Object} YouTubeDetectorConfig
* @property {string} [state] - Feature state: 'enabled', 'disabled', or 'internal'
* @property {string[]} playerSelectors - Selectors for the player root element
* @property {string[]} adClasses - CSS classes that indicate ads
* @property {string[]} adTextPatterns - Text patterns (regex) that indicate ads
* @property {number} sweepIntervalMs - How often to check for ads/buffering (ms)
* @property {number} slowLoadThresholdMs - Threshold for counting slow loads as buffering (ms)
* @property {{background: string, thumbnail: string, image: string}} staticAdSelectors
* @property {string[]} playabilityErrorSelectors
* @property {string[]} playabilityErrorPatterns
* @property {string[]} adBlockerDetectionSelectors
* @property {string[]} adBlockerDetectionPatterns
* @property {{signInButton: string, avatarButton: string, premiumLogo: string}} loginStateSelectors
* @property {Record<string, boolean>} [fireDetectionEvents] - Per-type gating for event firing. Only types set to `true` fire events. Absent = no events.
*/
/**
* YouTube Ad Detector
* Detects ads, buffering, playability errors, and ad blocker detection on YouTube
* All configuration comes from privacy-config - no hardcoded defaults
*/
/** @type {{info: Function, warn: Function, error: Function}} */
const noopLogger = { info: () => {}, warn: () => {}, error: () => {} };
export class YouTubeAdDetector {
/**
* @param {YouTubeDetectorConfig} config - Configuration from privacy-config (required)
* @param {{info: Function, warn: Function, error: Function}} [logger] - Optional logger from ContentFeature
* @param {(type: string) => void} [onEvent] - Callback fired when a new detection occurs
*/
constructor(config, logger, onEvent) {
// Logger for debug output (only logs when debug mode is enabled)
this.log = logger || noopLogger;
/** @type {(type: string) => void} */
this.onEvent = onEvent || (() => {});
// All config comes from privacy-config
this.config = {
playerSelectors: config.playerSelectors,
adClasses: config.adClasses,
adTextPatterns: config.adTextPatterns,
sweepIntervalMs: config.sweepIntervalMs,
slowLoadThresholdMs: config.slowLoadThresholdMs,
staticAdSelectors: config.staticAdSelectors,
playabilityErrorSelectors: config.playabilityErrorSelectors,
playabilityErrorPatterns: config.playabilityErrorPatterns,
adBlockerDetectionSelectors: config.adBlockerDetectionSelectors,
adBlockerDetectionPatterns: config.adBlockerDetectionPatterns,
loginStateSelectors: config.loginStateSelectors,
fireDetectionEvents: config.fireDetectionEvents,
};
// Initialize state
this.state = this.createInitialState();
// Intervals and tracking
this.pollInterval = null;
this.rerootInterval = null;
this.trackedVideoElement = null;
this.lastLoggedVideoId = null;
this.currentVideoId = null;
this.videoLoadStartTime = null;
this.bufferingStartTime = null;
this.lastSweepTime = null;
this.lastSeekTime = null;
this.playerRoot = null;
// Compiled regex patterns
this.adTextPatterns = toRegExpArray(this.config.adTextPatterns);
this.playabilityErrorPatterns = toRegExpArray(this.config.playabilityErrorPatterns);
this.adBlockerDetectionPatterns = toRegExpArray(this.config.adBlockerDetectionPatterns);
// Cache selector string for hot path
this.cachedAdSelector =
this.config.adClasses && this.config.adClasses.length > 0 ? this.config.adClasses.map((cls) => '.' + cls).join(',') : null;
}
// =========================================================================
// State Management
// =========================================================================
createInitialState() {
return {
detections: {
videoAd: { count: 0, showing: false },
staticAd: { count: 0, showing: false },
playabilityError: { count: 0, showing: false, /** @type {string|null} */ lastMessage: null },
adBlocker: { count: 0, showing: false },
},
buffering: {
count: 0,
/** @type {number[]} */ durations: [],
},
videoLoads: 0,
/** @type {{state: string, isPremium: boolean, rawIndicators: Object}|null} */ loginState: null,
perfMetrics: {
/** @type {number[]} */ sweepDurations: [],
/** @type {number[]} */ adCheckDurations: [],
sweepCount: 0,
/** @type {number[]} */ top5SweepDurations: [],
/** @type {number[]} */ top5AdCheckDurations: [],
sweepsOver10ms: 0,
sweepsOver50ms: 0,
},
};
}
/**
* Report a detection event
* @param {'videoAd'|'staticAd'|'playabilityError'|'adBlocker'} type
* @param {Object} [details]
* @returns {boolean} Whether detection was new
*/
reportDetection(type, details = {}) {
const typeState = this.state.detections[type];
if (typeState.showing) {
if (!details.message || typeState.lastMessage === details.message) {
return false;
}
}
this.log.info(`Detection: ${type}`, details.message || '');
typeState.showing = true;
typeState.count++;
if (details.message && 'lastMessage' in typeState) {
typeState.lastMessage = details.message;
}
if (this.config.fireDetectionEvents?.[type]) {
try {
this.onEvent(`youtube_${type}`);
} catch {
// onEvent callback failure should never break detection
}
}
return true;
}
/**
* Clear a detection state
* @param {'videoAd'|'staticAd'|'playabilityError'|'adBlocker'} type
*/
clearDetection(type) {
const typeState = this.state.detections[type];
if (!typeState.showing) return;
typeState.showing = false;
if ('lastMessage' in typeState) {
typeState.lastMessage = null;
}
}
// =========================================================================
// Main Detection Loop
// =========================================================================
/**
* Run one sweep of all detection checks
* Called periodically by the poll interval
*/
sweep() {
const sweepStart = performance.now();
this.lastSweepTime = sweepStart;
const root = this.findPlayerRoot();
if (!root) return;
// Re-attach video listeners if needed
this.attachVideoListeners(root);
// Check for video ads
const adCheckStart = performance.now();
const hasVideoAd = this.checkForVideoAds(root);
const adCheckDuration = performance.now() - adCheckStart;
if (hasVideoAd && !this.state.detections.videoAd.showing) {
this.reportDetection('videoAd');
} else if (!hasVideoAd && this.state.detections.videoAd.showing) {
this.clearDetection('videoAd');
}
// Check for static ads
const hasStaticAd = this.checkForStaticAds();
if (hasStaticAd && !this.state.detections.staticAd.showing) {
this.reportDetection('staticAd');
} else if (!hasStaticAd && this.state.detections.staticAd.showing) {
this.clearDetection('staticAd');
}
// Check for playability errors
const playabilityError = this.checkForPlayabilityErrors();
if (playabilityError && !this.state.detections.playabilityError.showing) {
this.reportDetection('playabilityError', { message: playabilityError });
} else if (!playabilityError && this.state.detections.playabilityError.showing) {
this.clearDetection('playabilityError');
}
// Check for ad blocker detection modals
const adBlockerDetected = this.checkForAdBlockerModals();
if (adBlockerDetected && !this.state.detections.adBlocker.showing) {
this.reportDetection('adBlocker');
} else if (!adBlockerDetected && this.state.detections.adBlocker.showing) {
this.clearDetection('adBlocker');
}
// Track performance
this.trackSweepPerformance(sweepStart, adCheckDuration);
}
/**
* Track sweep performance metrics
* @param {number} sweepStart
* @param {number} adCheckDuration
*/
trackSweepPerformance(sweepStart, adCheckDuration) {
const sweepDuration = performance.now() - sweepStart;
const perf = this.state.perfMetrics;
perf.sweepDurations.push(sweepDuration);
perf.adCheckDurations.push(adCheckDuration);
perf.sweepCount++;
// Track top 5 worst
perf.top5SweepDurations.push(sweepDuration);
perf.top5SweepDurations.sort((a, b) => b - a);
if (perf.top5SweepDurations.length > 5) perf.top5SweepDurations.pop();
perf.top5AdCheckDurations.push(adCheckDuration);
perf.top5AdCheckDurations.sort((a, b) => b - a);
if (perf.top5AdCheckDurations.length > 5) perf.top5AdCheckDurations.pop();
if (sweepDuration > 10) perf.sweepsOver10ms++;
if (sweepDuration > 50) perf.sweepsOver50ms++;
// Keep last 50
if (perf.sweepDurations.length > 50) {
perf.sweepDurations.shift();
perf.adCheckDurations.shift();
}
}
// =========================================================================
// Detection Helpers
// =========================================================================
/**
* Check if a node looks like an ad
* @param {Node} node
* @returns {boolean}
*/
looksLikeAdNode(node) {
if (!(node instanceof HTMLElement)) return false;
const classList = node.classList;
const adClasses = this.config.adClasses;
if (classList && adClasses && adClasses.some((adClass) => classList.contains(adClass))) {
return true;
}
const txt = (node.innerText || '') + ' ' + (node.getAttribute('aria-label') || '');
const patterns = this.adTextPatterns;
return patterns && patterns.some((pattern) => pattern.test(txt));
}
/**
* Check for visible video ads in the player
* @param {Element} root - Player root element
* @returns {boolean}
*/
checkForVideoAds(root) {
if (!this.cachedAdSelector) {
return false;
}
// Check if root itself has an ad class (e.g., ad-showing on #movie_player)
if (root.matches && root.matches(this.cachedAdSelector)) {
this.log.info('Ad detected: root element matches ad selector');
return true;
}
// Check for child elements with ad classes
const adElements = root.querySelectorAll(this.cachedAdSelector);
const hasAd = Array.from(adElements).some((el) => isVisible(el) && this.looksLikeAdNode(el));
if (hasAd) {
this.log.info('Ad detected: child element matches ad selector');
}
return hasAd;
}
/**
* Check for static overlay ads (image ads over the player)
* @returns {boolean}
*/
checkForStaticAds() {
const selectors = this.config.staticAdSelectors;
if (!selectors || !selectors.background) {
return false;
}
const background = document.querySelector(selectors.background);
if (!background || !isVisible(background)) {
return false;
}
const thumbnail = document.querySelector(selectors.thumbnail);
const image = document.querySelector(selectors.image);
if (!thumbnail && !image) {
return false;
}
/** @type {HTMLVideoElement | null} */
const video = document.querySelector('#movie_player video, .html5-video-player video');
const videoNotPlaying = !video || (video.paused && video.currentTime < 1);
if (image) {
const img = image.querySelector('img');
if (img && img.src && isVisible(image)) {
return true;
}
}
if (thumbnail && isVisible(thumbnail) && videoNotPlaying) {
return true;
}
return false;
}
/**
* Check for visible elements matching selectors and text patterns
* @param {string[]} selectors
* @param {RegExp[]} patterns
* @param {Object} [options]
* @returns {string|null} Matched text or null
*/
checkVisiblePatternMatch(selectors, patterns, options = {}) {
if (!selectors || !selectors.length || !patterns || !patterns.length) {
return null;
}
const maxLen = options.maxLength || 100;
const checkAttributedStrings = options.checkAttributedStrings || false;
const checkDialogFallback = options.checkDialogFallback || false;
for (const selector of selectors) {
const el = /** @type {HTMLElement | null} */ (document.querySelector(selector));
if (el && isVisible(el)) {
const text = el.innerText || el.textContent || '';
for (const pattern of patterns) {
if (pattern.test(text)) {
return text.trim().substring(0, maxLen);
}
}
if (checkAttributedStrings) {
const attributedStrings = el.querySelectorAll('.yt-core-attributed-string[role="text"]');
for (const attrEl of attributedStrings) {
const attrText = attrEl.textContent || '';
for (const pattern of patterns) {
if (pattern.test(attrText)) {
return attrText.trim().substring(0, maxLen);
}
}
}
}
}
}
if (checkDialogFallback) {
const bodyText = document.body?.innerText || '';
for (const pattern of patterns) {
if (pattern.test(bodyText)) {
const dialogs = document.querySelectorAll('[role="dialog"], [aria-modal="true"], .ytd-popup-container');
for (const dialog of dialogs) {
if (dialog instanceof HTMLElement && isVisible(dialog)) {
const dialogText = dialog.innerText || '';
if (pattern.test(dialogText)) {
return dialogText.trim().substring(0, maxLen);
}
}
}
}
}
}
return null;
}
/**
* Check for playability errors (bot detection, content blocking)
* @returns {string|null}
*/
checkForPlayabilityErrors() {
return this.checkVisiblePatternMatch(this.config.playabilityErrorSelectors, this.playabilityErrorPatterns, {
maxLength: 100,
checkAttributedStrings: true,
});
}
/**
* Check for ad blocker detection modals
* @returns {string|null}
*/
checkForAdBlockerModals() {
return this.checkVisiblePatternMatch(this.config.adBlockerDetectionSelectors, this.adBlockerDetectionPatterns, {
maxLength: 150,
checkDialogFallback: true,
});
}
// =========================================================================
// DOM Queries
// =========================================================================
/**
* Find the YouTube player root element
* @returns {Element|null}
*/
findPlayerRoot() {
if (!this.config.playerSelectors || !this.config.playerSelectors.length) {
return null;
}
for (const selector of this.config.playerSelectors) {
const el = document.querySelector(selector);
if (el) return el;
}
return null;
}
/**
* Get current video ID from URL
* @returns {string|null}
*/
getVideoId() {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get('v');
}
// =========================================================================
// Login State Detection
// =========================================================================
/**
* Detect YouTube user login state using DOM elements
* @returns {{state: string, isPremium: boolean, rawIndicators: Object}}
*/
detectLoginState() {
const selectors = this.config.loginStateSelectors;
// Return unknown if selectors not configured
if (!selectors) {
return { state: 'unknown', isPremium: false, rawIndicators: {} };
}
const indicators = {
hasSignInButton: false,
hasAvatarButton: false,
hasPremiumLogo: false,
};
try {
indicators.hasSignInButton = !!document.querySelector(selectors.signInButton);
indicators.hasAvatarButton = !!document.querySelector(selectors.avatarButton);
indicators.hasPremiumLogo = !!document.querySelector(selectors.premiumLogo);
} catch {
// Silently handle selector errors
}
let loginState = 'unknown';
if (indicators.hasPremiumLogo) {
loginState = 'premium';
} else if (indicators.hasAvatarButton) {
loginState = 'logged-in';
} else if (indicators.hasSignInButton) {
loginState = 'logged-out';
}
return {
state: loginState,
isPremium: indicators.hasPremiumLogo,
rawIndicators: indicators,
};
}
/**
* Detect login state with retries for timing issues
* @param {number} [attempt=1]
*/
detectAndLogLoginState(attempt = 1) {
if (this.state.loginState?.state && this.state.loginState.state !== 'unknown') {
return;
}
const loginState = this.detectLoginState();
if (loginState.state !== 'unknown' || attempt >= 5) {
this.state.loginState = loginState;
} else {
const delay = attempt * 500;
setTimeout(() => this.detectAndLogLoginState(attempt + 1), delay);
}
}
// =========================================================================
// Video Tracking
// =========================================================================
/**
* Attach event listeners to video element for tracking
* @param {Element} root - Player root element
* @param {number} [attempt=1] - Current retry attempt
*/
attachVideoListeners(root, attempt = 1) {
const videoElement = /** @type {HTMLVideoElement | null} */ (root?.querySelector('video'));
if (!videoElement) {
if (attempt < 25) {
setTimeout(() => this.attachVideoListeners(root, attempt + 1), 500);
}
return;
}
if (this.trackedVideoElement === videoElement) return;
this.trackedVideoElement = videoElement;
const onLoadStart = () => {
const vid = this.getVideoId();
if (vid && vid !== this.lastLoggedVideoId) {
this.lastLoggedVideoId = vid;
this.currentVideoId = vid;
this.videoLoadStartTime = performance.now();
this.state.videoLoads++;
}
};
const onPlaying = () => {
if (this.bufferingStartTime) {
const bufferingDuration = performance.now() - this.bufferingStartTime;
this.state.buffering.durations.push(Math.round(bufferingDuration));
// Cap durations array to prevent memory growth
if (this.state.buffering.durations.length > 50) {
this.state.buffering.durations.shift();
}
this.bufferingStartTime = null;
}
if (!this.videoLoadStartTime) return;
const loadTime = performance.now() - this.videoLoadStartTime;
const isSlow = loadTime > this.config.slowLoadThresholdMs;
const duringAd = this.state.detections.videoAd.showing;
const tabWasHidden = document.hidden;
const tooLong = loadTime > 30000;
if (isSlow && !duringAd && !tabWasHidden && !tooLong) {
this.state.buffering.count++;
this.state.buffering.durations.push(Math.round(loadTime));
// Cap durations array to prevent memory growth
if (this.state.buffering.durations.length > 50) {
this.state.buffering.durations.shift();
}
}
this.videoLoadStartTime = null;
};
const onWaiting = () => {
if (this.state.detections.videoAd.showing) return;
if (videoElement.currentTime < 0.5) return;
const recentlySeekd = this.lastSeekTime && performance.now() - this.lastSeekTime < 3000;
if (videoElement.seeking || recentlySeekd) return;
if (!this.bufferingStartTime) {
this.bufferingStartTime = performance.now();
this.state.buffering.count++;
}
};
const onSeeking = () => {
this.lastSeekTime = performance.now();
};
videoElement.addEventListener('loadstart', onLoadStart);
videoElement.addEventListener('playing', onPlaying);
videoElement.addEventListener('waiting', onWaiting);
videoElement.addEventListener('seeking', onSeeking);
// Track video ID for fresh navigation
const vid = this.getVideoId();
if (vid && vid !== this.lastLoggedVideoId) {
this.lastLoggedVideoId = vid;
this.currentVideoId = vid;
this.state.videoLoads++;
}
}
// =========================================================================
// SPA Navigation
// =========================================================================
// =========================================================================
// Lifecycle
// =========================================================================
/**
* Start the detector
* @param {number} [attempt=1] - Current retry attempt
*/
start(attempt = 1) {
this.log.info('YouTubeAdDetector starting...');
const root = this.findPlayerRoot();
if (!root) {
if (attempt < 25) {
this.log.info(`Player root not found, retrying in 500ms (attempt ${attempt}/25)`);
setTimeout(() => this.start(attempt + 1), 500);
} else {
this.log.info('Player root not found after 25 attempts, giving up');
}
return;
}
this.playerRoot = root;
this.log.info('Player root found:', root.id || root.className);
// Initial login state detection
this.detectAndLogLoginState();
// Start video tracking
this.attachVideoListeners(root);
// Start sweep loop
this.sweep();
this.pollInterval = setInterval(() => this.sweep(), this.config.sweepIntervalMs || 2000);
this.log.info(`Detector started, sweep interval: ${this.config.sweepIntervalMs}ms`);
// Check for player root changes
this.rerootInterval = setInterval(() => {
const r = this.findPlayerRoot();
if (r && r !== this.playerRoot) {
this.playerRoot = r;
if (this.pollInterval) clearInterval(this.pollInterval);
this.pollInterval = setInterval(() => this.sweep(), this.config.sweepIntervalMs || 2000);
}
}, 1000);
}
/**
* Stop the detector
*/
stop() {
if (this.pollInterval) {
clearInterval(this.pollInterval);
this.pollInterval = null;
}
if (this.rerootInterval) {
clearInterval(this.rerootInterval);
this.rerootInterval = null;
}
}
// =========================================================================
// Results
// =========================================================================
/**
* Get detection results in standard format
* @returns {Object}
*/
getResults() {
const d = this.state.detections;
// Calculate buffering stats
const totalBufferingMs = this.state.buffering.durations.reduce((sum, dur) => sum + dur, 0);
const avgBufferingMs = this.state.buffering.durations.length > 0 ? totalBufferingMs / this.state.buffering.durations.length : 0;
const bufferAvgSec = Math.round(avgBufferingMs / 1000);
// Refresh login state if unknown
let loginState = this.state.loginState;
if (!loginState || loginState.state === 'unknown') {
const freshCheck = this.detectLoginState();
if (freshCheck.state !== 'unknown') {
this.state.loginState = freshCheck;
loginState = freshCheck;
}
}
// Calculate average sweep time (rounded to nearest ms for privacy)
const perf = this.state.perfMetrics;
let sweepAvgMs = null;
if (perf && perf.sweepCount > 0 && perf.sweepDurations.length > 0) {
const avg = perf.sweepDurations.reduce((a, b) => a + b, 0) / perf.sweepDurations.length;
sweepAvgMs = Math.round(avg);
}
return {
detected:
d.videoAd.count > 0 ||
d.staticAd.count > 0 ||
d.playabilityError.count > 0 ||
d.adBlocker.count > 0 ||
this.state.buffering.count > 0,
type: 'youtubeAds',
results: [
{
adsDetected: d.videoAd.count,
staticAdsDetected: d.staticAd.count,
playabilityErrorsDetected: d.playabilityError.count,
adBlockerDetectionCount: d.adBlocker.count,
bufferingCount: this.state.buffering.count,
bufferAvgSec,
userState: loginState?.state || 'unknown',
sweepAvgMs,
},
],
};
}
}
// =========================================================================
// Module-level singleton
// =========================================================================
/** @type {YouTubeAdDetector | null} */
let detectorInstance = null;
/**
* Run YouTube ad detection
* @param {YouTubeDetectorConfig} [config] - Configuration from privacy-config
* @returns {Object} Detection results in standard format
*/
/**
* @param {YouTubeDetectorConfig} [config] - Configuration from privacy-config
* @param {{info: Function, warn: Function, error: Function}} [logger] - Optional logger from ContentFeature
* @param {(type: string) => void} [fireEvent] - Callback fired when a new detection occurs
*/
export function runYoutubeAdDetection(config, logger, fireEvent) {
const hostname = window.location.hostname;
const isYouTube = hostname === 'youtube.com' || hostname.endsWith('.youtube.com');
const isTestDomain = hostname === 'privacy-test-pages.site' || hostname.endsWith('.privacy-test-pages.site');
if (!isYouTube && !isTestDomain) {
return { detected: false, type: 'youtubeAds', results: [] };
}
// Only run if explicitly enabled or internal
if (config?.state !== 'enabled' && config?.state !== 'internal') {
return { detected: false, type: 'youtubeAds', results: [] };
}
// If detector already exists, return its results (even if config is undefined)
if (detectorInstance) {
return detectorInstance.getResults();
}
// Can't initialize without config
if (!config) {
return { detected: false, type: 'youtubeAds', results: [] };
}
detectorInstance = new YouTubeAdDetector(config, logger, fireEvent);
detectorInstance.start();
return detectorInstance.getResults();
}