Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
2385 lines (2126 loc) · 96.7 KB
/
Copy pathcontent.js
File metadata and controls
2385 lines (2126 loc) · 96.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
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Rustam Panda - Content Script
* Developed by @abbyisonline
* Features:
* - Meta Ads Library GraphQL interceptor
* - Automated smooth pagination with anti-bot pacing
* - Campaign -> AdSet -> Ad folder tree hierarchy
* - AI Competitor Intelligence Analyzer with OpenRouter integration & Model Selection
* - System Prompt customization & Strategy Presets
* - Moody white-base theme with dark mode option
*/
(function () {
if (window.__ADSPY_CONTENT_INITIALIZED__) return;
window.__ADSPY_CONTENT_INITIALIZED__ = true;
console.log('[Rustam Panda] Initialized on Meta Ads Library. Developed by @abbyisonline.');
// State store
const capturedAds = new Map(); // key: ad_archive_id -> normalized ad object
let activeTab = 'all'; // 'all', 'evergreen', 'dynamic', 'video', 'image'
let viewMode = 'cards'; // 'cards', 'tree', or 'ai'
let searchQuery = '';
let sortBy = 'longest'; // 'longest', 'newest', 'variants'
let isPanelOpen = false;
let currentTheme = localStorage.getItem('adspy_theme') || 'light'; // Default to moody white base
const PANDA_IMG_URL = (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.getURL) ? chrome.runtime.getURL('icons/panda.jpg') : '';
// Auto-Scroll & Pagination Collector state
let isAutoScrolling = false;
let autoScrollTimer = null;
let autoScrollTargetLimit = 0; // 0 = unlimited / all
let consecutiveNoNewAdsCount = 0;
let lastCapturedCount = 0;
// --- AI INTELLIGENCE & OPENROUTER STATE ---
let openRouterApiKey = '';
try { openRouterApiKey = localStorage.getItem('rustam_openrouter_key') || ''; } catch(e){}
let selectedAiModel = 'anthropic/claude-3.5-sonnet';
try { selectedAiModel = localStorage.getItem('rustam_ai_model') || 'anthropic/claude-3.5-sonnet'; } catch(e){}
let customAiModel = '';
try { customAiModel = localStorage.getItem('rustam_custom_model') || ''; } catch(e){}
let isAiAnalyzing = false;
let lastAiAnalysisReport = '';
try { lastAiAnalysisReport = localStorage.getItem('rustam_last_analysis') || ''; } catch(e){}
let aiAnalysisScope = 'all'; // 'all', 'evergreen', 'filtered', or specific ad_id
let singleTargetAdId = null;
// Load permanent API key and AI settings from Chrome Extension Storage
if (typeof chrome !== 'undefined' && chrome.storage) {
if (chrome.storage.sync) {
chrome.storage.sync.get(['rustam_openrouter_key', 'rustam_custom_model', 'rustam_ai_model', 'rustam_custom_prompt'], (res) => {
if (chrome.runtime.lastError || !res) return;
if (res.rustam_openrouter_key) {
openRouterApiKey = res.rustam_openrouter_key;
try { localStorage.setItem('rustam_openrouter_key', openRouterApiKey); } catch(e){}
}
if (res.rustam_custom_model) customAiModel = res.rustam_custom_model;
if (res.rustam_ai_model) selectedAiModel = res.rustam_ai_model;
if (res.rustam_custom_prompt) customSystemPrompt = res.rustam_custom_prompt;
});
}
if (chrome.storage.local) {
chrome.storage.local.get(['rustam_openrouter_key', 'rustam_custom_model', 'rustam_ai_model', 'rustam_custom_prompt'], (res) => {
if (chrome.runtime.lastError || !res) return;
if (res.rustam_openrouter_key && !openRouterApiKey) {
openRouterApiKey = res.rustam_openrouter_key;
try { localStorage.setItem('rustam_openrouter_key', openRouterApiKey); } catch(e){}
}
if (res.rustam_custom_model && !customAiModel) customAiModel = res.rustam_custom_model;
if (res.rustam_ai_model && !selectedAiModel) selectedAiModel = res.rustam_ai_model;
if (res.rustam_custom_prompt && !customSystemPrompt) customSystemPrompt = res.rustam_custom_prompt;
});
}
if (chrome.storage.onChanged) {
chrome.storage.onChanged.addListener((changes) => {
if (changes.rustam_openrouter_key) {
openRouterApiKey = changes.rustam_openrouter_key.newValue || '';
try { localStorage.setItem('rustam_openrouter_key', openRouterApiKey); } catch(e){}
}
if (changes.rustam_custom_model) {
customAiModel = changes.rustam_custom_model.newValue || '';
}
if (changes.rustam_ai_model) {
selectedAiModel = changes.rustam_ai_model.newValue || selectedAiModel;
populateModelSelector();
}
});
}
}
let openRouterModelsList = [];
let isFetchingModels = false;
try {
const cachedModels = localStorage.getItem('rustam_cached_models');
if (cachedModels) {
const parsed = JSON.parse(cachedModels);
if (Array.isArray(parsed) && parsed.length > 0) {
openRouterModelsList = parsed;
}
}
} catch (e) {
openRouterModelsList = [];
}
const TOP_RECOMMENDED_MODELS = [
{ id: 'anthropic/claude-3.5-sonnet', name: 'Claude 3.5 Sonnet (Recommended)' },
{ id: 'openai/gpt-4o', name: 'GPT-4o (Flagship)' },
{ id: 'openai/gpt-4o-mini', name: 'GPT-4o Mini (Fast & Cheap)' },
{ id: 'google/gemini-2.0-flash-001', name: 'Gemini 2.0 Flash (Super Fast)' },
{ id: 'deepseek/deepseek-chat', name: 'DeepSeek V3 (Top Value)' },
{ id: 'deepseek/deepseek-r1', name: 'DeepSeek R1 (Deep Reasoning)' },
{ id: 'meta-llama/llama-3.3-70b-instruct', name: 'Llama 3.3 70B' },
{ id: 'mistralai/mistral-large-2411', name: 'Mistral Large' }
];
function updateFetchModelBtnUI(isFetching) {
const btn = document.getElementById('adspy-btn-fetch-models');
if (!btn) return;
if (isFetching) {
btn.classList.add('adspy-fetching');
btn.innerHTML = `${lucide('refresh-cw', '', 11)} <span>Fetching...</span>`;
btn.disabled = true;
} else {
btn.classList.remove('adspy-fetching');
const count = openRouterModelsList.length > 0 ? ` (${openRouterModelsList.length})` : '';
btn.innerHTML = `${lucide('refresh-cw', '', 11)} <span>Fetch Models${count}</span>`;
btn.disabled = false;
}
}
function populateModelSelector() {
const select = document.getElementById('adspy-select-model');
if (!select) return;
const currentVal = selectedAiModel || 'anthropic/claude-3.5-sonnet';
const recIds = new Set(TOP_RECOMMENDED_MODELS.map(m => m.id));
let html = '';
html += '<optgroup label="⭐ Top Recommended">';
TOP_RECOMMENDED_MODELS.forEach(m => {
const isSel = (currentVal === m.id) ? 'selected' : '';
html += `<option value="${escapeHtml(m.id)}" ${isSel}>${escapeHtml(m.name)}</option>`;
});
html += '</optgroup>';
if (Array.isArray(openRouterModelsList) && openRouterModelsList.length > 0) {
const liveModels = openRouterModelsList.filter(m => m && m.id && !recIds.has(m.id));
html += `<optgroup label="🌐 Live OpenRouter Models (${openRouterModelsList.length} total)">`;
liveModels.forEach(m => {
const isSel = (currentVal === m.id) ? 'selected' : '';
const displayName = m.name && m.name !== m.id ? `${m.name} (${m.id})` : m.id;
html += `<option value="${escapeHtml(m.id)}" ${isSel}>${escapeHtml(displayName)}</option>`;
});
html += '</optgroup>';
}
html += '<optgroup label="⚙️ Custom">';
const customSel = (currentVal === 'custom') ? 'selected' : '';
html += `<option value="custom" ${customSel}>Custom Model Slug...</option>`;
html += '</optgroup>';
select.innerHTML = html;
let found = false;
for (let i = 0; i < select.options.length; i++) {
if (select.options[i].value === currentVal) {
found = true;
break;
}
}
if (!found && currentVal && currentVal !== 'custom') {
const opt = document.createElement('option');
opt.value = currentVal;
opt.textContent = `${currentVal} (Selected)`;
opt.selected = true;
select.insertBefore(opt, select.firstChild);
}
select.value = currentVal;
}
async function fetchOpenRouterModels(force = false) {
if (isFetchingModels) return;
if (!force && openRouterModelsList && openRouterModelsList.length > 0) {
populateModelSelector();
updateFetchModelBtnUI(false);
return;
}
isFetchingModels = true;
updateFetchModelBtnUI(true);
try {
const headers = {
'HTTP-Referer': 'https://facebook.com/ads/library',
'X-Title': 'Rustam Panda'
};
if (openRouterApiKey && openRouterApiKey.trim()) {
headers['Authorization'] = `Bearer ${openRouterApiKey.trim()}`;
}
const res = await fetch('https://openrouter.ai/api/v1/models', {
method: 'GET',
headers
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}: Failed to fetch models`);
}
const json = await res.json();
if (json && Array.isArray(json.data) && json.data.length > 0) {
openRouterModelsList = json.data.map(m => ({
id: m.id,
name: m.name || m.id,
context_length: m.context_length || 0
})).sort((a, b) => (a.name || a.id).localeCompare(b.name || b.id));
try {
localStorage.setItem('rustam_cached_models', JSON.stringify(openRouterModelsList));
} catch (e) {}
populateModelSelector();
showNotification(`Fetched ${openRouterModelsList.length} models from OpenRouter!`, 'success');
} else {
throw new Error('No models returned from OpenRouter');
}
} catch (err) {
console.warn('[Rustam Panda] OpenRouter models fetch failed:', err);
if (force) {
showNotification(`Could not fetch models: ${err.message}`, 'warning');
}
} finally {
isFetchingModels = false;
updateFetchModelBtnUI(false);
}
}
const DEFAULT_SYSTEM_PROMPTS = {
strategy: `You are Rustam Panda AI, an elite media buyer, competitive intelligence analyst, and direct-response advertising strategist.
Analyze the provided competitor ads data from Meta Ads Library.
Generate a comprehensive, actionable, and executive-level Competitor Intelligence Dossier.
Structure your report clearly with the following sections:
1. 🎯 EXECUTIVE SUMMARY & CORE POSITIONING: What are they selling, what is their primary value proposition, and how aggressively are they scaling?
2. 👥 TARGET AUDIENCE PERSONAS & PAIN POINTS: Identify their primary customer avatars, acute pain points exploited, and emotional triggers used.
3. 🎣 WINNING HOOKS & ANGLES: Analyze their top hooks, opening angles, and psychological frameworks.
4. 🧱 FUNNEL & OFFER TEARDOWN: Analyze their Call-To-Actions, landing page destinations, UTM parameters, and conversion strategy.
5. ⚔️ COUNTER-ATTACK STRATEGY & 3 WINNING AD SCRIPTS: Provide 3 concrete, battle-tested counter-ad concepts (Hook, Copy, Creative direction) that an advertiser can run to beat this competitor in the Meta ad auction.`,
copywriting: `You are Rustam Panda AI, a master direct-response copywriter.
Analyze the competitor's ad copy, headlines, and calls to action.
Break down:
1. 💡 PSYCHOLOGICAL TRIGGERS: Urgency, social proof, curiosity, transformation, and status.
2. ✍️ HEADLINE & HOOK FORMULAS: Deconstruct their top-performing hook structures into reusable formulas.
3. 🎯 OFFER ARCHITECTURE: Guarantees, bonuses, pricing psychology, and risk reversal.
4. 📝 3 PLUG-AND-PLAY COPY TEMPLATES: Create 3 high-converting ad copy templates inspired by this competitor's proven winners.`,
evergreen: `You are Rustam Panda AI, a performance marketing expert specializing in scale and ad fatigue.
Analyze the competitor's longest-running (Evergreen) ads.
Break down:
1. 🔥 THE SCALING ENGINE: Why have these specific ads run for weeks/months without fatiguing?
2. 🎨 CREATIVE FORMATS: Video vs Image vs Carousel distribution and visual hook mechanics.
3. 🛡️ AD FATIGUE RESISTANCE: How they vary copy/creative to maintain high ROAS.
4. 🚀 ACTION PLAN: Exactly how to produce a winning creative asset that achieves similar evergreen lifespan.`,
single: `You are Rustam Panda AI. Analyze this specific Meta ad creative in forensic detail.
Break down:
1. 🎣 THE HOOK: Why this hook grabs attention in the feed (psychological trigger).
2. 📖 CORE MESSAGE & PAIN POINTS: The narrative, mechanism of action, and customer objection addressed.
3. 🎯 CTA & DESTINATION: How the ad primes the user for the landing page.
4. 🚀 2 VARIANT HOOKS: Suggest 2 alternative high-converting hooks for this exact concept.`
};
let selectedSystemPromptKey = localStorage.getItem('rustam_prompt_key') || 'strategy';
let customSystemPrompt = localStorage.getItem('rustam_custom_prompt') || DEFAULT_SYSTEM_PROMPTS[selectedSystemPromptKey];
// --- LUCIDE SVG ICONS SYSTEM ---
function lucide(name, className = '', size = 16) {
const icons = {
'sparkles': `<path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/>`,
'folder': `<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>`,
'folder-open': `<path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/>`,
'sun': `<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>`,
'moon': `<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>`,
'download': `<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>`,
'copy': `<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>`,
'check': `<polyline points="20 6 9 17 4 12"/>`,
'play': `<polygon points="6 3 20 12 6 21 6 3"/>`,
'square': `<rect width="18" height="18" x="3" y="3" rx="2"/>`,
'search': `<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>`,
'filter': `<polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/>`,
'layers': `<polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/>`,
'flame': `<path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/>`,
'external-link': `<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>`,
'x': `<path d="M18 6 6 18"/><path d="M6 6l12 12"/>`,
'chevron-right': `<path d="m9 18 6-6-6-6"/>`,
'chevron-down': `<path d="m6 9 6 6 6-6"/>`,
'calendar': `<rect width="18" height="18" x="3" y="4" rx="2" ry="2"/><line x1="16" x2="16" y1="2" y2="6"/><line x1="8" x2="8" y1="2" y2="6"/><line x1="3" x2="21" y1="10" y2="10"/>`,
'video': `<path d="m22 8-6 4 6 4V8Z"/><rect width="14" height="12" x="2" y="6" rx="2" ry="2"/>`,
'image': `<rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>`,
'target': `<circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/>`,
'link': `<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>`,
'grid': `<rect width="7" height="7" x="3" y="3" rx="1"/><rect width="7" height="7" x="14" y="3" rx="1"/><rect width="7" height="7" x="14" y="14" rx="1"/><rect width="7" height="7" x="3" y="14" rx="1"/>`,
'brain': `<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M12 5v13"/>`,
'settings': `<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>`,
'refresh-cw': `<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/>`,
'zap': `<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>`,
'file-text': `<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><polyline points="14 2 14 8 20 8"/><line x1="16" x2="8" y1="13" y2="13"/><line x1="16" x2="8" y1="17" y2="17"/><line x1="10" x2="8" y1="9" y2="9"/>`,
'printer': `<polyline points="6 9 6 2 18 2 18 9"></polyline><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path><rect width="12" height="8" x="6" y="14"></rect>`,
'key': `<circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/>`
};
const path = icons[name] || icons['sparkles'];
return `<svg class="lucide lucide-${name} ${className}" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${path}</svg>`;
}
// URL Helper to unmask Facebook redirect URLs (e.g., https://l.facebook.com/l.php?u=...)
function unmaskUrl(url) {
if (!url) return '';
try {
if (url.includes('facebook.com/l.php')) {
const parsed = new URL(url);
const target = parsed.searchParams.get('u');
if (target) {
return decodeURIComponent(target);
}
}
} catch (e) {}
return url;
}
// Parse UTM parameters and funnel tracking tags from URL
function extractTrackingParams(rawUrl) {
const cleanUrl = unmaskUrl(rawUrl);
if (!cleanUrl) return { cleanUrl: '', fullUrl: '', domain: '', params: {} };
try {
const urlObj = new URL(cleanUrl);
const params = {};
const utmKeys = [
'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term',
'fbclid', 'gclid', 'ref', 'source', 'campaign_id', 'adset_id', 'ad_id', 'pixel_id',
'campaign', 'adset', 'ad'
];
urlObj.searchParams.forEach((value, key) => {
const lowerKey = key.toLowerCase();
if (utmKeys.includes(lowerKey) || lowerKey.startsWith('utm_')) {
params[key] = value;
}
});
return {
cleanUrl: cleanUrl.split('?')[0],
fullUrl: cleanUrl,
domain: urlObj.hostname.replace(/^www\./, ''),
params: params
};
} catch (e) {
return { cleanUrl: cleanUrl, fullUrl: cleanUrl, domain: '', params: {} };
}
}
// Normalize timestamp to readable format and days active
function calculateLifespan(startTimestamp, endTimestamp) {
if (!startTimestamp) return { startDate: 'Unknown', daysRunning: 0, isEvergreen: false };
const startMs = startTimestamp > 100000000000 ? startTimestamp : startTimestamp * 1000;
const startDate = new Date(startMs);
const now = Date.now();
const diffTime = Math.max(0, now - startMs);
const daysRunning = Math.floor(diffTime / (1000 * 60 * 60 * 24));
return {
startDate: startDate.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }),
startTime: startDate.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }),
daysRunning: daysRunning,
isEvergreen: daysRunning >= 21
};
}
// Recursive search for ad objects inside GraphQL JSON tree
function findAdNodes(node, results = []) {
if (!node || typeof node !== 'object') return results;
if (node.ad_archive_id || (node.snapshot && (node.snapshot.body || node.snapshot.link_url || node.snapshot.images))) {
results.push(node);
return results;
}
if (Array.isArray(node)) {
for (const item of node) {
findAdNodes(item, results);
}
} else {
for (const key of Object.keys(node)) {
findAdNodes(node[key], results);
}
}
return results;
}
// Normalize ad node into standard structure
function normalizeAd(raw) {
const archiveId = String(raw.ad_archive_id || raw.archive_id || raw.id || `ad_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`);
const snapshot = raw.snapshot || {};
// Ad Copy / Primary Text
let bodyText = '';
if (typeof snapshot.body === 'string') {
bodyText = snapshot.body;
} else if (snapshot.body && snapshot.body.markup && snapshot.body.markup.__html) {
try {
const doc = new DOMParser().parseFromString(snapshot.body.markup.__html, 'text/html');
bodyText = (doc && doc.body) ? (doc.body.textContent || doc.body.innerText || '') : '';
} catch (e) {
bodyText = String(snapshot.body.markup.__html).replace(/<[^>]*>?/gm, '');
}
} else if (snapshot.body && typeof snapshot.body.text === 'string') {
bodyText = snapshot.body.text;
}
// Headline & Link Info
const headline = snapshot.title || snapshot.headline || '';
const caption = snapshot.caption || snapshot.display_url || '';
const linkDescription = snapshot.link_description || '';
const ctaText = snapshot.cta_text || snapshot.cta_title || snapshot.call_to_action_title || '';
const ctaType = snapshot.cta_type || '';
// Destination URL & UTM Tracking Breakdown
const rawLinkUrl = snapshot.link_url || snapshot.link || '';
const trackingInfo = extractTrackingParams(rawLinkUrl);
// Media: Images
const images = [];
if (Array.isArray(snapshot.images)) {
snapshot.images.forEach(img => {
const url = img.original_image_url || img.resized_image_url || (typeof img === 'string' ? img : '');
if (url && !images.includes(url)) images.push(url);
});
}
// Media: Videos
const videos = [];
if (Array.isArray(snapshot.videos)) {
snapshot.videos.forEach(vid => {
const hd = vid.video_hd_url || vid.hd_url || '';
const sd = vid.video_sd_url || vid.sd_url || '';
const preview = vid.video_preview_image_url || vid.preview_url || '';
if (hd || sd) {
videos.push({
hdUrl: hd,
sdUrl: sd,
preview: preview,
downloadUrl: hd || sd
});
}
});
}
// Carousel Cards
const cards = [];
if (Array.isArray(snapshot.cards)) {
snapshot.cards.forEach(card => {
const cardTrack = extractTrackingParams(card.link_url || '');
cards.push({
title: card.title || '',
body: card.body || '',
linkUrl: cardTrack.fullUrl,
cleanUrl: cardTrack.cleanUrl,
imageUrl: card.image_url || card.original_image_url || '',
videoUrl: card.video_hd_url || card.video_sd_url || ''
});
});
}
// Platforms
let platforms = raw.publisher_platform || raw.publisher_platforms || [];
if (!Array.isArray(platforms)) platforms = [platforms].filter(Boolean);
if (platforms.length === 0 && raw.platforms) platforms = raw.platforms;
// Timestamps and Active duration
const startTimestamp = raw.start_date || raw.creation_time || snapshot.creation_time;
const endTimestamp = raw.end_date || raw.stop_time;
const lifespan = calculateLifespan(startTimestamp, endTimestamp);
// Dynamic Creative Variations (Collation)
const collationCount = raw.collation_count || (raw.collated_results ? raw.collated_results.length : 1);
const collationId = raw.collation_id || null;
// EU Transparency & Demographic Targeting
const euTransparency = raw.eu_transparency || {};
const demographicTargeting = {
ages: euTransparency.target_ages || raw.target_ages || null,
gender: euTransparency.target_gender || raw.target_gender || null,
locations: euTransparency.target_locations || raw.target_locations || null,
reach: euTransparency.eu_total_reach || null,
beneficiary: euTransparency.beneficiary_name || raw.beneficiary_name || null,
payer: euTransparency.payer_name || raw.payer_name || null
};
// Page Info
const pageId = raw.page_id || snapshot.page_id || raw.page_info?.id || '';
const pageName = raw.page_name || snapshot.page_name || raw.page_info?.name || 'Meta Advertiser';
const pageProfilePic = snapshot.page_profile_picture_url || raw.page_profile_picture_url || '';
// Campaign & AdSet Folder Mapping
const p = trackingInfo.params;
const campaignName = p.utm_campaign || p.campaign || p.campaign_id || (pageName ? `${pageName} Campaign` : 'Core Marketing Campaign');
const adsetName = p.utm_content || p.adset || p.adset_id || p.utm_term || (collationId ? `Variant Set #${collationId}` : 'Target Audience Set');
return {
id: archiveId,
pageId,
pageName,
pageProfilePic,
bodyText,
headline,
caption,
linkDescription,
ctaText,
ctaType,
trackingInfo,
images,
videos,
cards,
platforms,
lifespan,
collationCount,
collationId,
demographicTargeting,
campaignName,
adsetName,
isActive: raw.is_active !== undefined ? raw.is_active : true,
spend: raw.spend || null,
impressions: raw.impressions_with_index || raw.impressions || null
};
}
// Handle incoming GraphQL intercepted messages
window.addEventListener('message', (event) => {
if (event.data && event.data.type === 'ADSPY_RAW_GRAPHQL') {
const payload = event.data.payload;
const adNodes = findAdNodes(payload);
let newCount = 0;
adNodes.forEach(node => {
const normalized = normalizeAd(node);
if (normalized.id && !capturedAds.has(normalized.id)) {
capturedAds.set(normalized.id, normalized);
newCount++;
}
});
if (newCount > 0) {
updateBadgeCounter();
if (viewMode !== 'ai') {
renderView();
}
}
}
});
// --- UI CREATION ---
function injectOverlayUI() {
if (document.getElementById('adspy-root')) return;
const root = document.createElement('div');
root.id = 'adspy-root';
root.className = `adspy-theme-${currentTheme}`;
root.innerHTML = `
<!-- Floating Pill Launcher -->
<div id="adspy-pill" class="adspy-pill" title="Click to open Rustam Panda">
<div class="adspy-pill-avatar">
<img src="${PANDA_IMG_URL}" alt="Rustam Panda" class="adspy-panda-avatar" />
</div>
<div class="adspy-pill-text">
<span class="adspy-pill-title">Rustam Panda</span>
<span id="adspy-pill-count" class="adspy-pill-count">0 Ads</span>
</div>
<div class="adspy-pulse"></div>
</div>
<!-- Moody Dark & Blur Screen Backdrop -->
<div id="adspy-backdrop" class="adspy-backdrop adspy-hidden" title="Click outside to close"></div>
<!-- Main Studio Panel -->
<div id="adspy-panel" class="adspy-panel adspy-hidden">
<!-- Header -->
<div class="adspy-header">
<div class="adspy-brand">
<div class="adspy-logo">
<img src="${PANDA_IMG_URL}" alt="Rustam Panda" class="adspy-header-panda-img" />
</div>
<div>
<div class="adspy-title">Rustam Panda</div>
<div class="adspy-subtitle">developed by <a href="https://t.me/abbyisonline" target="_blank" rel="noopener noreferrer" class="adspy-author" style="text-decoration:none; color:inherit;">@abbyisonline</a></div>
</div>
</div>
<div class="adspy-header-actions">
<!-- AI Intelligence Analyzer Trigger -->
<button id="adspy-btn-header-ai" class="adspy-btn adspy-btn-secondary" title="AI Competitor Intelligence Analyzer">
${lucide('brain', '', 14)}
AI Intelligence
</button>
<!-- Theme Toggle (Light / Dark) -->
<button id="adspy-btn-theme" class="adspy-btn adspy-btn-secondary" title="Switch Theme (Light/Dark)">
${currentTheme === 'dark' ? lucide('sun', '', 14) : lucide('moon', '', 14)}
<span id="adspy-theme-text">${currentTheme === 'dark' ? 'Light' : 'Dark'}</span>
</button>
<!-- Export Folder Tree JSON -->
<button id="adspy-btn-export-tree" class="adspy-btn adspy-btn-secondary" title="Export Folder Hierarchy (Campaign -> AdSet -> Ads)">
${lucide('folder', '', 14)}
Folder JSON
</button>
<!-- Export CSV -->
<button id="adspy-btn-export-csv" class="adspy-btn adspy-btn-secondary" title="Export CSV for Excel / Sheets">
${lucide('download', '', 14)}
CSV
</button>
<button id="adspy-btn-close" class="adspy-btn-icon" title="Close Panel">
${lucide('x', '', 16)}
</button>
</div>
</div>
<!-- Metric Counter Bar -->
<div class="adspy-stats-bar">
<div class="adspy-stat-item">
<div class="adspy-stat-value" id="adspy-stat-total">0</div>
<div class="adspy-stat-label">Total Ads</div>
</div>
<div class="adspy-stat-item">
<div class="adspy-stat-value" id="adspy-stat-campaigns">0</div>
<div class="adspy-stat-label">Campaign Folders</div>
</div>
<div class="adspy-stat-item">
<div class="adspy-stat-value" id="adspy-stat-evergreen">0</div>
<div class="adspy-stat-label">Evergreen Winners (>21d)</div>
</div>
<div class="adspy-stat-item">
<div class="adspy-stat-value" id="adspy-stat-dynamic">0</div>
<div class="adspy-stat-label">Multi-Variants</div>
</div>
</div>
<!-- Toolbar & Pagination Control -->
<div class="adspy-toolbar">
<!-- Auto-Scroll / Pagination Section -->
<div class="adspy-autoscroll-bar">
<div class="adspy-autoscroll-controls">
<button id="adspy-btn-autoscroll" class="adspy-btn adspy-btn-autoscroll" title="Automatically paginate through all ads">
<span id="adspy-autoscroll-icon">${lucide('play', '', 13)}</span>
<span id="adspy-btn-autoscroll-text">Auto-Scroll & Collect</span>
</button>
<div class="adspy-limit-box">
<label for="adspy-select-limit">Target:</label>
<select id="adspy-select-limit" class="adspy-select">
<option value="0">All Ads</option>
<option value="25">25 Ads</option>
<option value="50">50 Ads</option>
<option value="100">100 Ads</option>
<option value="200">200 Ads</option>
</select>
</div>
</div>
<div id="adspy-autoscroll-status" class="adspy-autoscroll-status adspy-hidden">
<span class="adspy-spinner"></span>
<span id="adspy-autoscroll-text">Auto-collecting ads...</span>
</div>
<!-- View Switcher: Card Grid vs Folder Tree vs AI -->
<div class="adspy-view-toggle">
<button class="adspy-view-btn active" id="adspy-btn-view-cards" title="Cards Grid View">
${lucide('grid', '', 13)} Cards
</button>
<button class="adspy-view-btn" id="adspy-btn-view-tree" title="Campaign -> AdSet -> Ad Folder Tree View">
${lucide('folder', '', 13)} Folders
</button>
<button class="adspy-view-btn" id="adspy-btn-view-ai" title="AI Competitor Intelligence Analyzer">
${lucide('brain', '', 13)} AI Insights
</button>
</div>
</div>
<!-- Search & Filters -->
<div class="adspy-filter-row" id="adspy-filter-row">
<div class="adspy-search-wrapper">
<span class="adspy-search-icon">${lucide('search', '', 14)}</span>
<input type="text" id="adspy-search-input" placeholder="Search copy, headlines, UTM campaigns, domains..." />
</div>
<div class="adspy-sort-wrapper">
<span class="adspy-sort-label">Sort:</span>
<select id="adspy-select-sort" class="adspy-select">
<option value="longest">Longest Running (Evergreen)</option>
<option value="newest">Newest First</option>
<option value="variants">Most Variants</option>
</select>
</div>
</div>
<!-- Filter Pills -->
<div class="adspy-tabs" id="adspy-tabs-row">
<button class="adspy-tab active" data-tab="all">All Ads</button>
<button class="adspy-tab" data-tab="evergreen">${lucide('flame', '', 12)} Evergreen (>21d)</button>
<button class="adspy-tab" data-tab="dynamic">${lucide('layers', '', 12)} Dynamic Variants</button>
<button class="adspy-tab" data-tab="video">${lucide('video', '', 12)} Videos</button>
<button class="adspy-tab" data-tab="image">${lucide('image', '', 12)} Images</button>
</div>
</div>
<!-- Dynamic Feed Content Container -->
<div id="adspy-content-view" class="adspy-content-view">
<!-- Populated by renderView() -->
</div>
</div>
<!-- AI Settings Modal Container -->
<div id="adspy-modal-container"></div>
`;
document.body.appendChild(root);
// Event listeners
const pillBtn = document.getElementById('adspy-pill');
if (pillBtn) pillBtn.addEventListener('click', togglePanel);
const closeBtn = document.getElementById('adspy-btn-close');
if (closeBtn) closeBtn.addEventListener('click', togglePanel);
const backdropEl = document.getElementById('adspy-backdrop');
if (backdropEl) backdropEl.addEventListener('click', togglePanel);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && isPanelOpen) {
togglePanel();
}
});
// Theme Toggle
const themeBtn = document.getElementById('adspy-btn-theme');
if (themeBtn) themeBtn.addEventListener('click', toggleTheme);
// Exports
const exportTreeBtn = document.getElementById('adspy-btn-export-tree');
if (exportTreeBtn) exportTreeBtn.addEventListener('click', exportFolderTreeJSON);
const exportCsvBtn = document.getElementById('adspy-btn-export-csv');
if (exportCsvBtn) exportCsvBtn.addEventListener('click', exportCSV);
// View Switchers
const btnCards = document.getElementById('adspy-btn-view-cards');
const btnTree = document.getElementById('adspy-btn-view-tree');
const btnAi = document.getElementById('adspy-btn-view-ai');
const btnHeaderAi = document.getElementById('adspy-btn-header-ai');
function setActiveView(mode) {
viewMode = mode;
[btnCards, btnTree, btnAi].forEach(b => {
if (b) b.classList.remove('active');
});
const filterRow = document.getElementById('adspy-filter-row');
const tabsRow = document.getElementById('adspy-tabs-row');
if (mode === 'cards') {
if (btnCards) btnCards.classList.add('active');
if (filterRow) filterRow.style.display = 'flex';
if (tabsRow) tabsRow.style.display = 'flex';
} else if (mode === 'tree') {
if (btnTree) btnTree.classList.add('active');
if (filterRow) filterRow.style.display = 'flex';
if (tabsRow) tabsRow.style.display = 'flex';
} else if (mode === 'ai') {
if (btnAi) btnAi.classList.add('active');
if (filterRow) filterRow.style.display = 'none';
if (tabsRow) tabsRow.style.display = 'none';
}
renderView();
}
if (btnCards) btnCards.addEventListener('click', () => setActiveView('cards'));
if (btnTree) btnTree.addEventListener('click', () => setActiveView('tree'));
if (btnAi) btnAi.addEventListener('click', () => setActiveView('ai'));
if (btnHeaderAi) btnHeaderAi.addEventListener('click', () => setActiveView('ai'));
// Auto-Scroll listeners
const autoScrollBtn = document.getElementById('adspy-btn-autoscroll');
const limitSelect = document.getElementById('adspy-select-limit');
if (limitSelect) {
limitSelect.addEventListener('change', (e) => {
autoScrollTargetLimit = parseInt(e.target.value, 10) || 0;
});
}
if (autoScrollBtn) {
autoScrollBtn.addEventListener('click', () => {
if (isAutoScrolling) {
stopAutoScroll('Paused by user');
} else {
startAutoScroll();
}
});
}
// Search and Sort
const searchInput = document.getElementById('adspy-search-input');
if (searchInput) {
searchInput.addEventListener('input', (e) => {
searchQuery = e.target.value.toLowerCase();
renderView();
});
}
const sortSelect = document.getElementById('adspy-select-sort');
if (sortSelect) {
sortSelect.addEventListener('change', (e) => {
sortBy = e.target.value;
renderView();
});
}
// Tabs
const tabs = (root && root.querySelectorAll) ? root.querySelectorAll('.adspy-tab') : [];
tabs.forEach(tab => {
if (tab) {
tab.addEventListener('click', () => {
tabs.forEach(t => { if (t) t.classList.remove('active'); });
tab.classList.add('active');
activeTab = tab.getAttribute('data-tab');
renderView();
});
}
});
}
// Toggle Theme (White / Dark mode)
function toggleTheme() {
currentTheme = currentTheme === 'dark' ? 'light' : 'dark';
try {
localStorage.setItem('adspy_theme', currentTheme);
} catch (e) {}
const root = document.getElementById('adspy-root');
if (root) {
root.className = `adspy-theme-${currentTheme}`;
}
const themeBtn = document.getElementById('adspy-btn-theme');
if (themeBtn) {
themeBtn.innerHTML = `
${currentTheme === 'dark' ? lucide('sun', '', 14) : lucide('moon', '', 14)}
<span id="adspy-theme-text">${currentTheme === 'dark' ? 'Light' : 'Dark'}</span>
`;
}
}
// --- AUTOMATED PAGINATION & SCROLL ENGINE ---
function startAutoScroll() {
if (isAutoScrolling) return;
isAutoScrolling = true;
consecutiveNoNewAdsCount = 0;
lastCapturedCount = capturedAds.size;
const btn = document.getElementById('adspy-btn-autoscroll');
const btnText = document.getElementById('adspy-btn-autoscroll-text');
const iconSpan = document.getElementById('adspy-autoscroll-icon');
const statusBox = document.getElementById('adspy-autoscroll-status');
const statusText = document.getElementById('adspy-autoscroll-text');
const pill = document.getElementById('adspy-pill');
if (btn) {
btn.classList.add('adspy-btn-autoscroll-active');
if (btnText) btnText.textContent = 'Stop Auto-Scroll';
if (iconSpan) iconSpan.innerHTML = lucide('square', '', 13);
}
if (statusBox) statusBox.classList.remove('adspy-hidden');
if (statusText) statusText.textContent = `Auto-collecting (0 / ${autoScrollTargetLimit > 0 ? autoScrollTargetLimit : '∞'})...`;
if (pill) pill.classList.add('adspy-pill-scrolling');
console.log('[Rustam Panda] Auto-scroll pagination loop active.');
stepAutoScroll();
}
function stopAutoScroll(reason = '') {
if (!isAutoScrolling) return;
isAutoScrolling = false;
if (autoScrollTimer) {
clearTimeout(autoScrollTimer);
autoScrollTimer = null;
}
const btn = document.getElementById('adspy-btn-autoscroll');
const btnText = document.getElementById('adspy-btn-autoscroll-text');
const iconSpan = document.getElementById('adspy-autoscroll-icon');
const statusBox = document.getElementById('adspy-autoscroll-status');
const statusText = document.getElementById('adspy-autoscroll-text');
const pill = document.getElementById('adspy-pill');
if (btn) {
btn.classList.remove('adspy-btn-autoscroll-active');
if (btnText) btnText.textContent = 'Auto-Scroll & Collect';
if (iconSpan) iconSpan.innerHTML = lucide('play', '', 13);
}
if (pill) pill.classList.remove('adspy-pill-scrolling');
if (reason && statusText) {
statusText.textContent = reason;
setTimeout(() => {
if (!isAutoScrolling && statusBox) statusBox.classList.add('adspy-hidden');
}, 3500);
} else if (statusBox) {
statusBox.classList.add('adspy-hidden');
}
}
function stepAutoScroll() {
if (!isAutoScrolling) return;
if (autoScrollTargetLimit > 0 && capturedAds.size >= autoScrollTargetLimit) {
stopAutoScroll(`Target reached: ${autoScrollTargetLimit} ads!`);
return;
}
const statusText = document.getElementById('adspy-autoscroll-text');
if (statusText) {
const targetStr = autoScrollTargetLimit > 0 ? autoScrollTargetLimit : 'All';
statusText.textContent = `Auto-collecting: ${capturedAds.size} / ${targetStr} ads`;
}
if (capturedAds.size > lastCapturedCount) {
consecutiveNoNewAdsCount = 0;
lastCapturedCount = capturedAds.size;
} else {
consecutiveNoNewAdsCount++;
}
if (consecutiveNoNewAdsCount >= 4) {
const candidates = Array.from(document.querySelectorAll('div[role="button"], button, a[role="button"]'));
let clickedButton = false;
for (const el of candidates) {
// Never click elements within our own extension overlay
if (el.closest && el.closest('#adspy-root')) continue;
const txt = (el.textContent || '').trim().toLowerCase();
// Specifically match feed-level pagination buttons, never ad copy 'see more' accordions
const isPaginationBtn = (txt.includes('more results') || txt === 'retry' || txt === 'load more' || txt.includes('reload results'));
if (isPaginationBtn && el.offsetParent !== null) {
try {
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
setTimeout(() => {
try { el.click(); } catch (err) {}
}, 400);
clickedButton = true;
consecutiveNoNewAdsCount = 1;
break;
} catch (err) {}
}
}
if (!clickedButton && consecutiveNoNewAdsCount >= 7) {
stopAutoScroll(`Finished! Reached end of ads (${capturedAds.size} total captured).`);
return;
}
}
const scrollHeight = Math.max(
document.documentElement.scrollHeight,
document.body.scrollHeight,
window.scrollY + window.innerHeight
);
window.scrollTo({
top: scrollHeight,
behavior: 'smooth'
});
window.dispatchEvent(new Event('scroll', { bubbles: true }));
document.dispatchEvent(new Event('scroll', { bubbles: true }));
const delay = Math.floor(Math.random() * 600) + 1400;
autoScrollTimer = setTimeout(stepAutoScroll, delay);
}
// Handle messages from extension popup
if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.onMessage) {
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
try {
if (request.action === 'GET_STATUS') {
sendResponse({
totalAds: capturedAds.size,
isAutoScrolling: isAutoScrolling
});
} else if (request.action === 'START_AUTO_SCROLL') {