-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcontent-simple.js
More file actions
1975 lines (1681 loc) · 80 KB
/
content-simple.js
File metadata and controls
1975 lines (1681 loc) · 80 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
// ULTRA SIMPLE - COPIE EXACTE DU PYTHON
let isRunning = false;
let config = {};
let appliedCount = 0;
let skippedCount = 0;
let appliedJobs = []; // Liste des jobs appliqués pour export
let lastActivityTime = Date.now(); // Track last activity for stuck detection
let lastJobIndex = -1; // Track last job processed
const STUCK_TIMEOUT = 120000; // 2 minutes without activity = stuck
// SECURITY: Ultimate protection flag - bot can ONLY run if user explicitly clicked Start
let userExplicitlyClickedStart = false;
// Resume/CV data for automatic upload
let resumeFile = null; // Base64 data
let resumeFileName = null;
let resumeFileType = null;
// Logs simples
function log(msg) {
console.log('[LinkedIn Bot]', msg);
try {
chrome.runtime.sendMessage({ type: 'log', message: msg });
} catch (e) {}
}
// Attendre
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Cliquer - PROTECTED: Only works if bot is running
async function click(element) {
// CRITICAL SECURITY CHECK: Prevent ANY clicks if bot is not explicitly started
if (!isRunning || !userExplicitlyClickedStart) {
console.error('🚨 SECURITY VIOLATION: Attempted click() but bot is NOT running!');
console.error('🔒 isRunning:', isRunning, '| userExplicitlyClickedStart:', userExplicitlyClickedStart);
console.error('🚫 Click BLOCKED for security');
console.trace('Call stack:'); // Show where this was called from
return; // BLOCK THE CLICK
}
element.click();
updateActivity(); // Update activity on every click
await wait(500);
}
// Update last activity time
function updateActivity() {
lastActivityTime = Date.now();
}
// Check if script is stuck (no activity for STUCK_TIMEOUT)
function isStuck() {
const timeSinceActivity = Date.now() - lastActivityTime;
return timeSinceActivity > STUCK_TIMEOUT;
}
// Check for LinkedIn's daily Easy Apply limit
function checkDailyLimit() {
try {
// List of limit message patterns (case-insensitive)
const limitPatterns = [
"You've reached today's Easy Apply limit",
"You've reached today's easy apply limit",
"reached today's Easy Apply limit",
"Great effort applying today",
"we limit daily submissions",
"continue applying tomorrow",
"Save this job and continue applying tomorrow",
"exceeded the daily application limit",
"reached today\\'s easy apply limit",
"daily Easy Apply limit",
"limit daily submissions"
];
// Search in entire page text
const bodyText = document.body.innerText || '';
for (const pattern of limitPatterns) {
if (bodyText.toLowerCase().includes(pattern.toLowerCase())) {
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
log('🚫 DAILY LIMIT REACHED!');
log(` Message detected: "${pattern}"`);
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
log('LinkedIn limits Easy Apply to ~50-100 per day');
log('📊 Session stats:');
log(` ✅ Applied: ${appliedCount}`);
log(` ⏭️ Skipped: ${skippedCount}`);
log('⏰ You can continue applying tomorrow!');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
// Show visual notification to user
alert(`🚫 LinkedIn Daily Limit Reached!\n\n` +
`You've reached LinkedIn's daily Easy Apply limit (~50-100 applications).\n\n` +
`📊 Today's Stats:\n` +
` ✅ Applied: ${appliedCount}\n` +
` ⏭️ Skipped: ${skippedCount}\n\n` +
`⏰ You can continue applying tomorrow!\n\n` +
`The bot has been stopped automatically.`);
return true;
}
}
// Also check for specific error messages in modal/toast elements
const errorElements = document.querySelectorAll('.artdeco-inline-feedback, .artdeco-toast-item, .artdeco-modal__content');
for (const element of errorElements) {
const elementText = element.textContent || '';
for (const pattern of limitPatterns) {
if (elementText.toLowerCase().includes(pattern.toLowerCase())) {
log('🚫 DAILY LIMIT DETECTED in error element!');
return true;
}
}
}
return false;
} catch (error) {
log(`⚠️ Error checking daily limit: ${error.message}`);
return false;
}
}
// IMPROVED: Function to find and click Done button with exhaustive search
async function findAndClickDoneButton(contextElement = document, contextName = 'page', maxAttempts = 15) {
log(`🔍 [${contextName}] Starting exhaustive search for Done button...`);
const doneTexts = ['Done', 'Terminé', 'Submit application', 'Soumettre la candidature', 'Dismiss', 'Close', 'Fermer'];
let doneBtn = null;
for (let attempt = 0; attempt < maxAttempts && !doneBtn; attempt++) {
await wait(1000);
// Log what we're looking for on first attempt
if (attempt === 0) {
log(` Looking for buttons with text: ${doneTexts.join(', ')}`);
}
// METHOD 1: Search by SPAN text (Python method - most reliable)
for (let targetText of doneTexts) {
// Find ALL spans in context
const spans = Array.from(contextElement.querySelectorAll('span.artdeco-button__text, span'));
for (let span of spans) {
const spanText = span.textContent.trim();
if (spanText === targetText) {
// Find clickable parent
let clickableElement = span.closest('button, [role="button"], .artdeco-button');
if (!clickableElement) {
clickableElement = span;
}
// Check if visible
if (clickableElement.offsetParent !== null) {
doneBtn = clickableElement;
log(` ✅ [METHOD 1] Found via SPAN: "${targetText}"`);
break;
}
}
}
if (doneBtn) break;
}
// METHOD 2: Direct button search (fallback)
if (!doneBtn) {
const buttons = Array.from(contextElement.querySelectorAll('button, [role="button"]'));
for (let btn of buttons) {
const btnText = btn.textContent.trim();
for (let targetText of doneTexts) {
if (btnText === targetText && btn.offsetParent !== null) {
doneBtn = btn;
log(` ✅ [METHOD 2] Found via direct button search: "${targetText}"`);
break;
}
}
if (doneBtn) break;
}
}
// METHOD 3: Search by aria-label
if (!doneBtn) {
for (let targetText of doneTexts) {
const ariaBtn = contextElement.querySelector(`button[aria-label*="${targetText}"], [role="button"][aria-label*="${targetText}"]`);
if (ariaBtn && ariaBtn.offsetParent !== null) {
doneBtn = ariaBtn;
log(` ✅ [METHOD 3] Found via aria-label: "${targetText}"`);
break;
}
}
}
// METHOD 4: Search by data-control-name (LinkedIn specific)
if (!doneBtn) {
const controlNames = ['done', 'submit', 'continue_application'];
for (let name of controlNames) {
const controlBtn = contextElement.querySelector(`button[data-control-name*="${name}"]`);
if (controlBtn && controlBtn.offsetParent !== null) {
doneBtn = controlBtn;
log(` ✅ [METHOD 4] Found via data-control-name: "${name}"`);
break;
}
}
}
// Debug: Log all visible buttons on first and every 5th attempt
if (attempt === 0 || attempt % 5 === 0) {
if (!doneBtn) {
const allButtons = Array.from(contextElement.querySelectorAll('button, [role="button"]'));
const visibleButtons = allButtons.filter(b => b.offsetParent !== null);
log(` [DEBUG Attempt ${attempt + 1}/${maxAttempts}] Found ${visibleButtons.length} visible buttons:`);
visibleButtons.slice(0, 10).forEach((btn, i) => {
const text = btn.textContent.trim().substring(0, 30);
const ariaLabel = btn.getAttribute('aria-label') || 'none';
const dataControl = btn.getAttribute('data-control-name') || 'none';
log(` ${i + 1}. Text: "${text}" | Aria: "${ariaLabel}" | Data: "${dataControl}"`);
});
}
}
if (!doneBtn && (attempt === 0 || attempt % 5 === 0)) {
log(` ⏳ [${contextName}] Attempt ${attempt + 1}/${maxAttempts}: Still searching...`);
}
}
// Try to click if found
if (doneBtn) {
log(`✅✅✅ [${contextName}] Done button FOUND! Attempting click...`);
let clickSuccessful = false;
// Method 1: Standard click
try {
log(' Click Method 1: Standard click...');
doneBtn.click();
await wait(500);
log(' ✅ Standard click successful');
clickSuccessful = true;
} catch (e1) {
log(` ⚠️ Standard click failed: ${e1.message}`);
// Method 2: MouseEvent
try {
log(' Click Method 2: MouseEvent dispatch...');
doneBtn.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
await wait(500);
log(' ✅ MouseEvent click successful');
clickSuccessful = true;
} catch (e2) {
log(` ⚠️ MouseEvent failed: ${e2.message}`);
// Method 3: Focus + Enter
try {
log(' Click Method 3: Keyboard Enter...');
doneBtn.focus();
await wait(200);
doneBtn.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true }));
doneBtn.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true }));
await wait(500);
log(' ✅ Keyboard trigger successful');
clickSuccessful = true;
} catch (e3) {
log(` ❌ All click methods failed: ${e3.message}`);
}
}
}
if (clickSuccessful) {
updateActivity();
await wait(700); // Ultra optimized job card click wait
return { success: true, clicked: true };
} else {
return { success: false, clicked: false, reason: 'Click failed' };
}
} else {
log(`❌ [${contextName}] Done button NOT FOUND after ${maxAttempts} attempts`);
return { success: false, clicked: false, reason: 'Button not found' };
}
}
// Refresh page and return to job search
async function refreshAndReturnToSearch() {
log('🔄 REFRESHING page due to stuck detection...');
try {
// Reload the page
location.reload();
// Wait will happen automatically when page reloads
return true;
} catch (error) {
log(`❌ Error refreshing page: ${error.message}`);
return false;
}
}
// Discard application (Python ligne 1500-1580) - ULTRA AGGRESSIVE VERSION + STUCK DETECTION
async function discardApplication() {
log('🚀 DISCARD: Starting SAFE discard sequence...');
const discardTexts = ['discard', 'annuler', 'cancel', 'abandonner', 'descarter'];
try {
// 🆕 DETECTION CRITIQUE: Vérifier si popup de chargement est bloqué (Python ligne 1547-1558)
if (checkForStuckLoadingPopup()) {
log('🚨 POPUP DE CHARGEMENT BLOQUÉ DÉTECTÉ!');
log('🔄 REFRESH DE LA PAGE POUR DÉBLOQUER...');
try {
location.reload();
await wait(2000); // Optimized refresh wait
log('✅ Page rafraîchie avec succès');
return true;
} catch (error) {
log(`❌ Erreur lors du refresh: ${error.message}`);
}
}
// STEP 1: Force close with X button (MOST RELIABLE METHOD - moved to first)
log('🔍 STEP 1: Looking for X/Close button...');
const closeButtons = document.querySelectorAll('button[aria-label*="Dismiss"], button[aria-label*="Close"], button.artdeco-modal__dismiss');
for (let btn of closeButtons) {
if (btn.offsetParent) {
log(`✅ Clicking close button: ${btn.getAttribute('aria-label')}`);
btn.click();
await wait(1000);
// Look for discard confirmation again
const discardBtn = Array.from(document.querySelectorAll('button')).find(b =>
b.offsetParent && discardTexts.some(t => b.textContent.trim().toLowerCase().includes(t))
);
if (discardBtn) {
log('✅ Clicking discard confirmation');
discardBtn.click();
await wait(1500);
}
const modal = document.querySelector('.jobs-easy-apply-modal');
if (!modal || modal.offsetParent === null) {
log('✅✅✅ MODAL CLOSED!');
return true;
}
}
}
// STEP 2: Press ESC key (fallback)
log('📤 STEP 2: Pressing ESC key...');
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true }));
document.dispatchEvent(new KeyboardEvent('keyup', { key: 'Escape', keyCode: 27, bubbles: true }));
await wait(1000); // Optimized ESC wait
// STEP 3: Look for ANY discard/cancel button (last resort)
log('🔍 STEP 3: Searching for Discard/Cancel buttons...');
// Try 3 times to find the button (it may appear slowly)
for (let attempt = 1; attempt <= 3; attempt++) {
log(` Attempt ${attempt}/3...`);
// Get ALL buttons on page (including in dialogs/modals)
const allButtons = Array.from(document.querySelectorAll('button, [role="button"]'));
log(` Found ${allButtons.length} total buttons`);
for (let btn of allButtons) {
// Skip invisible buttons
if (!btn.offsetParent) continue;
// Get text from button and nested elements
const btnText = btn.textContent.trim().toLowerCase();
const ariaLabel = (btn.getAttribute('aria-label') || '').toLowerCase();
const dataControl = (btn.getAttribute('data-control-name') || '').toLowerCase();
// Check if it's a discard/cancel button
const isDiscardButton = discardTexts.some(text =>
btnText === text ||
btnText.includes(text) ||
ariaLabel.includes(text) ||
dataControl.includes(text)
);
if (isDiscardButton) {
log(`✅ FOUND: "${btn.textContent.trim()}" (visible, will click)`);
// Click with multiple methods
try {
btn.click();
await wait(300);
btn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
} catch (e) {
log(`⚠️ Click error: ${e.message}`);
}
await wait(1500);
// Check if modal closed
const modal = document.querySelector('.jobs-easy-apply-modal');
if (!modal || modal.offsetParent === null) {
log('✅✅✅ MODAL CLOSED SUCCESSFULLY!');
return true;
}
}
}
await wait(1000); // Wait before retry
}
log('❌ DISCARD FAILED: Could not close modal after all attempts');
return false;
} catch (error) {
log(`❌ Error discarding: ${error.message}`);
return false;
}
}
// Remplir un champ - PROTECTED: Only works if bot is running
function fill(input, value) {
// CRITICAL SECURITY CHECK: Prevent ANY form filling if bot is not explicitly started
if (!isRunning || !userExplicitlyClickedStart) {
console.error('🚨 SECURITY VIOLATION: Attempted fill() but bot is NOT running!');
console.error('🔒 isRunning:', isRunning, '| userExplicitlyClickedStart:', userExplicitlyClickedStart);
console.error('🚫 Fill BLOCKED for security');
return; // BLOCK THE FILL
}
input.value = value;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
// Convert base64 to File object for resume upload
function base64ToFile(base64String, filename, mimeType) {
try {
// Remove data URL prefix if present (e.g., "data:application/pdf;base64,")
const base64Data = base64String.includes(',') ? base64String.split(',')[1] : base64String;
// Convert base64 to binary
const binaryString = atob(base64Data);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// Create File object
const file = new File([bytes], filename, { type: mimeType });
return file;
} catch (error) {
log(`❌ Error converting base64 to file: ${error.message}`);
return null;
}
}
// Fill file input with resume
async function fillFileInput(fileInput, file) {
try {
// Create a DataTransfer object to set files
const dataTransfer = new DataTransfer();
dataTransfer.items.add(file);
// Set the files property
fileInput.files = dataTransfer.files;
// Trigger change event
fileInput.dispatchEvent(new Event('change', { bubbles: true }));
log(`✅ Resume uploaded: ${file.name}`);
return true;
} catch (error) {
log(`❌ Error filling file input: ${error.message}`);
return false;
}
}
// BOUCLE PRINCIPALE - EXACTEMENT COMME PYTHON
async function mainLoop() {
// SECURITY: Triple-layer protection - bot MUST be explicitly started by user
if (!isRunning) {
log('⚠️ SECURITY BLOCK 1/3: mainLoop called but isRunning=false - ABORTING');
return;
}
if (!userExplicitlyClickedStart) {
log('🚨 SECURITY BLOCK 2/3: mainLoop called but user did NOT click Start - ABORTING');
log('🔒 This prevents any automatic execution. Bot ONLY runs when you click Start.');
isRunning = false; // Force stop for safety
await chrome.storage.local.set({ isRunning: false });
return;
}
// Final sanity check
if (!config || !config.email) {
log('⚠️ SECURITY BLOCK 3/3: No config loaded - ABORTING');
isRunning = false;
userExplicitlyClickedStart = false;
await chrome.storage.local.set({ isRunning: false });
return;
}
console.log('%c━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'color: green; font-weight: bold;');
console.log('%c🚀 BOT STARTED - User clicked START button', 'color: green; font-weight: bold; font-size: 14px;');
console.log('%c✅ ALL SECURITY CHECKS PASSED', 'color: green; font-weight: bold;');
console.log('%c🔓 Click() and Fill() functions are now ENABLED', 'color: green; font-weight: bold;');
console.log('%c━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'color: green; font-weight: bold;');
log('🚀 ✅ ALL SECURITY CHECKS PASSED - Bot started by user');
// Detect page type ONCE at start
const isCollectionsPage = window.location.href.includes('/jobs/collections/');
if (isCollectionsPage) {
log('📋 Page type: COLLECTIONS (infinite scroll mode)');
} else {
log('📋 Page type: SEARCH (pagination mode)');
}
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
while (isRunning) {
try {
// 🆕 CHECK: Daily limit reached?
if (checkDailyLimit()) {
log('⛔ Stopping bot: Daily limit reached');
isRunning = false;
userExplicitlyClickedStart = false; // Clear security flag
// Update storage
await chrome.storage.local.set({ isRunning: false });
// Notify popup
try {
chrome.runtime.sendMessage({
type: 'updateStatus',
status: 'stopped',
message: 'Daily limit reached'
});
} catch (e) {
// Popup may be closed
}
break;
}
// 🆕 CHECK: Script stuck? (no activity for 2 minutes)
if (isStuck()) {
log('🚨 SCRIPT STUCK DETECTED: No activity for 2 minutes!');
log('🔄 Refreshing page to recover...');
await refreshAndReturnToSearch();
await wait(2500); // Optimized stuck recovery wait
updateActivity(); // Reset activity after refresh
continue;
}
// Python ligne 1695: job_listings = driver.find_elements(By.XPATH, "//li[@data-occludable-job-id]")
let jobCards = document.querySelectorAll('li[data-occludable-job-id]');
// ONLY on collections page: use fallback selectors if no jobs found with standard selector
if (jobCards.length === 0 && isCollectionsPage) {
jobCards = document.querySelectorAll('.jobs-search-results__list-item, .scaffold-layout__list-item');
if (jobCards.length > 0) {
log(`📋 Collections mode: found ${jobCards.length} jobs with fallback selectors`);
}
}
if (jobCards.length === 0) {
log(`Aucune offre trouvée. Attente 5s...`);
// Check if page is unrecognized (no jobs for too long)
if (isStuck()) {
log('🚨 Page might be unrecognized (no jobs found + stuck)');
log('🔄 Refreshing to return to job search...');
await refreshAndReturnToSearch();
await wait(2500); // Optimized refresh recovery wait
updateActivity();
}
await wait(2500); // Optimized no jobs wait
continue;
}
log(`${jobCards.length} offres trouvées`);
updateActivity(); // Found jobs = activity
// Python ligne 1701: for job in job_listings
for (let i = 0; i < jobCards.length; i++) {
if (!isRunning) break;
const job = jobCards[i];
const jobId = job.getAttribute('data-occludable-job-id');
log(`\n--- Job ${i + 1}/${jobCards.length} (ID: ${jobId}) ---`);
// CRITICAL: Check if modal from previous job is still open (stuck scenario)
const leftoverModal = document.querySelector('.jobs-easy-apply-modal');
if (leftoverModal && leftoverModal.offsetParent !== null) {
log('⚠️ WARNING: Modal from previous job still open! Cleaning up...');
await discardApplication();
await wait(1000); // Optimized cleanup wait
// Verify it's closed
const stillOpen = document.querySelector('.jobs-easy-apply-modal');
if (stillOpen && stillOpen.offsetParent !== null) {
log('❌ CRITICAL: Could not close leftover modal, skipping this job');
skippedCount++;
updateSkippedCount();
continue;
} else {
log('✅ Leftover modal cleaned up successfully');
}
}
// Get job info for filtering
// Use extended selectors ONLY on collections page
let jobTitle, jobCompany, jobDescription;
if (isCollectionsPage) {
jobTitle = job.querySelector('.job-card-list__title, .artdeco-entity-lockup__title, .job-card-container__link strong, a[class*="job-card"] strong')?.textContent.trim() || '';
jobCompany = job.querySelector('.job-card-container__primary-description, .artdeco-entity-lockup__subtitle, .artdeco-entity-lockup__caption')?.textContent.trim() || '';
jobDescription = job.querySelector('.job-card-container__metadata-item, .job-card-list__insight')?.textContent.trim() || '';
} else {
// Standard selectors for /jobs/search/
jobTitle = job.querySelector('.job-card-list__title, .artdeco-entity-lockup__title')?.textContent.trim() || '';
jobCompany = job.querySelector('.job-card-container__primary-description, .artdeco-entity-lockup__subtitle')?.textContent.trim() || '';
jobDescription = job.querySelector('.job-card-container__metadata-item')?.textContent.trim() || '';
}
// Check blacklist keywords
if (shouldSkipByBlacklist(jobTitle, jobCompany, jobDescription, config.blacklistKeywords)) {
skippedCount++;
updateSkippedCount();
continue;
}
// Check max years required
if (shouldSkipByExperience(job, parseInt(config.maxYearsRequired))) {
skippedCount++;
updateSkippedCount();
continue;
}
// Scroll and click (Python line 371)
job.scrollIntoView({ block: 'start', behavior: 'smooth' });
await wait(500);
const link = job.querySelector('a');
if (link) {
await click(link);
await wait(600); // Ultra optimized job link wait
}
// Chercher Easy Apply (Python ligne 1853)
let easyApplyBtn = document.querySelector('button.jobs-apply-button[aria-label*="Easy"]');
// ONLY on collections page: try additional selectors if not found
if (!easyApplyBtn && isCollectionsPage) {
// Try other Easy Apply selectors (must contain "Easy" to avoid external Apply)
easyApplyBtn = document.querySelector('button[aria-label*="Easy Apply"]');
if (easyApplyBtn) {
log('📋 Found Easy Apply with collections selector');
}
}
if (!easyApplyBtn) {
log('Pas Easy Apply, skip');
skippedCount++;
updateSkippedCount();
continue;
}
await click(easyApplyBtn);
await wait(800); // Ultra optimized Easy Apply wait
// Safety reminder modal ("Continue applying")
// LinkedIn sometimes shows a "Job search safety reminder" dialog
const safetyModal = document.querySelector('[role="dialog"], .artdeco-modal');
if (safetyModal && safetyModal.offsetParent !== null) {
const safetyText = safetyModal.textContent.toLowerCase();
if (safetyText.includes('safety reminder') || safetyText.includes('rappel de sécurité') ||
safetyText.includes('continue applying') || safetyText.includes('continuer à postuler')) {
log('Safety reminder detected — clicking Continue applying...');
const continueBtn = Array.from(safetyModal.querySelectorAll('button')).find(btn => {
const t = btn.textContent.trim().toLowerCase();
return t.includes('continue applying') || t.includes('continuer à postuler') ||
t.includes('continue') || t.includes('continuer');
});
if (continueBtn) {
await click(continueBtn);
log('Safety reminder dismissed');
await wait(1000);
}
}
}
// CRITICAL: Check for daily limit immediately after clicking Easy Apply
// This catches the network error case where modal doesn't appear
if (checkDailyLimit()) {
log('');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
log('🚫 LINKEDIN DAILY LIMIT REACHED!');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
log('LinkedIn limits Easy Apply to ~50-100 per day');
log(`✅ Applied today: ${appliedCount}`);
log(`⏭️ Skipped today: ${skippedCount}`);
log('⏰ You can continue applying tomorrow!');
log('🛑 Bot stopped automatically');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
log('');
isRunning = false;
userExplicitlyClickedStart = false; // Clear security flag
// Update storage
await chrome.storage.local.set({ isRunning: false });
try {
chrome.runtime.sendMessage({
type: 'updateStatus',
status: 'stopped',
message: 'Daily limit reached'
});
} catch (e) {
// Popup might be closed
}
break; // Exit job loop
}
// Verify that modal appeared (if not, might be limit reached)
const modalCheck = document.querySelector('.jobs-easy-apply-modal');
if (!modalCheck || modalCheck.offsetParent === null) {
log('⚠️ Easy Apply modal did not appear - checking for limit...');
await wait(1000); // Optimized modal check wait
if (checkDailyLimit()) {
log('');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
log('🚫 LINKEDIN DAILY LIMIT REACHED!');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
log('LinkedIn limits Easy Apply to ~50-100 per day');
log(`✅ Applied today: ${appliedCount}`);
log(`⏭️ Skipped today: ${skippedCount}`);
log('⏰ You can continue applying tomorrow!');
log('🛑 Bot stopped automatically');
log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
log('');
isRunning = false;
userExplicitlyClickedStart = false; // Clear security flag
// Update storage
await chrome.storage.local.set({ isRunning: false });
try {
chrome.runtime.sendMessage({
type: 'updateStatus',
status: 'stopped',
message: 'Daily limit reached'
});
} catch (e) {
// Popup might be closed
}
break; // Exit job loop
}
// Modal still not there and no limit message - skip job
log('❌ Modal did not appear (unknown reason), skipping job');
skippedCount++;
updateSkippedCount();
continue;
}
// Infos du job déjà extraites plus haut pour blacklist, on les réutilise
const jobLink = job.querySelector('a')?.href || window.location.href;
// Remplir formulaire multi-étapes avec TIMEOUT (Python ligne 528-529)
let step = 0;
const applicationStartTime = Date.now();
const applicationTimeout = 180000; // 3 minutes max par candidature
let loadingScreenTimeout = 20000; // 20 secondes pour écran de chargement (Python ligne 1481-1497)
let lastActivityTime = Date.now();
while (step < 10) {
step++;
// TIMEOUT CHECK (Python ligne 639)
if (Date.now() - applicationStartTime > applicationTimeout) {
log('⏰ TIMEOUT 3min - Discarding application');
await discardApplication();
skippedCount++;
updateSkippedCount();
break;
}
// 🆕 RE-CHECK: Popup bloqué avant chaque step (Python ligne 1563-1568)
if (checkForStuckLoadingPopup()) {
log('🚨 POPUP TOUJOURS BLOQUÉ - REFRESH...');
location.reload();
await wait(2000); // Optimized refresh wait
skippedCount++;
updateSkippedCount();
break;
}
// CHECK FOR VALIDATION ERRORS EARLY (stuck scenario)
let modal = document.querySelector('.jobs-easy-apply-modal');
if (modal) {
const errors = modal.querySelectorAll('[role="alert"], .artdeco-inline-feedback--error, .fb-form-element-label__error');
for (let error of errors) {
if (error.offsetParent !== null) {
const errorText = error.textContent.toLowerCase();
if (errorText.includes('please enter') ||
errorText.includes('valid answer') ||
errorText.includes('required') ||
errorText.includes('must be') ||
errorText.includes('invalid')) {
log(`❌ STUCK: Validation error detected: ${error.textContent.substring(0, 50)}`);
log('⚠️ Discarding application due to validation error');
await discardApplication();
skippedCount++;
updateSkippedCount();
step = 999; // Force break
break;
}
}
}
if (step === 999) break;
}
// CHECK LOADING SCREEN (Python ligne 1481-1497)
if (await isPageLoadingSlow()) {
log('⏳ Loading screen detected...');
const loadingStart = Date.now();
while (await isPageLoadingSlow()) {
if (Date.now() - loadingStart > loadingScreenTimeout) {
log('⏰ Loading screen TIMEOUT 20s - Discarding application');
// Use the discardApplication function to properly close modal
const discarded = await discardApplication();
if (discarded) {
log('✅ Modal closed successfully, moving to next job');
} else {
log('⚠️ Modal may not be closed, forcing break anyway');
}
skippedCount++;
updateSkippedCount();
// Wait to ensure modal is closed and page is stable
await wait(1000); // Optimized modal stable wait
// Exit the step loop to move to next job
break;
}
await wait(1000);
}
if (Date.now() - loadingStart > loadingScreenTimeout) {
break; // Sortir du while principal pour passer au job suivant
}
}
log(`Step ${step}`);
// Find modal (reuse variable from earlier)
modal = document.querySelector('.jobs-easy-apply-modal');
if (!modal) {
log('Modal closed');
break;
}
// 1. TEXT FIELDS (Python line 1102) - Multilingual support
const textInputs = modal.querySelectorAll('input[type="text"], input[type="email"], input[type="tel"], input[type="number"]');
for (let input of textInputs) {
if (input.value) continue; // Skip if already filled
// Get label from multiple sources
let labelText = '';
// aria-label
labelText += ' ' + (input.getAttribute('aria-label') || '');
// name attribute
labelText += ' ' + (input.getAttribute('name') || '');
// Associated <label> element
const inputId = input.getAttribute('id');
if (inputId) {
const labelEl = modal.querySelector(`label[for="${inputId}"]`);
if (labelEl) labelText += ' ' + labelEl.textContent;
}
// Parent label
const parentLabel = input.closest('label');
if (parentLabel) labelText += ' ' + parentLabel.textContent;
const label = labelText.toLowerCase();
// Years of experience (EN/FR/ES/DE/IT)
if (label.match(/experience|years|expérience|années|años|jahre|anni|esperienza/)) {
fill(input, config.yearsOfExperience || '2');
log(`Years exp: ${config.yearsOfExperience || '2'}`);
}
// Salary / Compensation (EN/FR/ES/DE/IT)
else if (label.match(/salary|compensation|remuneration|salaire|rémunération|sueldo|salario|gehalt|stipendio/)) {
if (config.expectedSalary) {
fill(input, config.expectedSalary);
log(`Salary filled: ${config.expectedSalary}`);
} else {
log(`⚠️ Salary question detected but no expected salary configured`);
}
}
// Email
else if (label.match(/email|e-mail|courriel|correo/)) fill(input, config.email);
// First name (EN/FR/ES/DE/IT)
else if (label.match(/first|prénom|prenom|nombre|vorname|nome/)) fill(input, config.firstName);
// Last name (EN/FR/ES/DE/IT)
else if (label.match(/last|nom|apellido|nachname|cognome/)) fill(input, config.lastName);
// Phone (EN/FR/ES/DE/IT) - includes "portable", "cell", "móvil"
else if (label.match(/phone|téléphone|telefono|telefon|mobile|portable|cell|móvil|cellulare/)) {
fill(input, config.phone);
log(`Phone filled: ${config.phone}`);
}
// City/Location (EN/FR/ES/DE/IT) - with autocomplete handling
else if (label.match(/city|ville|ciudad|stadt|città|location|localisation|ubicación|standort/)) {
fill(input, config.city || '');
log(`Location filled: ${config.city}`);
// Wait for autocomplete dropdown to appear
await wait(1000);
// Try multiple selectors for autocomplete dropdown
let dropdown = null;
const dropdownSelectors = [
'[role="listbox"]',
'.basic-typeahead__selectable',
'.artdeco-typeahead__results',
'.artdeco-dropdown__content-inner',
'ul[role="listbox"]',
'.typeahead-results'
];
for (let selector of dropdownSelectors) {
dropdown = document.querySelector(selector);
if (dropdown && dropdown.offsetParent !== null) { // Visible
break;
}
}
if (dropdown) {
// Find first option
const optionSelectors = [
'[role="option"]:first-child',
'li:first-child',
'.basic-typeahead__selectable-item:first-child'
];
let firstOption = null;
for (let selector of optionSelectors) {
firstOption = dropdown.querySelector(selector);
if (firstOption) break;
}
if (firstOption) {
firstOption.click();
log(`✓ Location autocomplete: ${firstOption.textContent.substring(0, 30)}`);
await wait(500);
}
} else {
// Fallback: Keyboard navigation (Arrow Down + Enter)
log('Using keyboard fallback for location');
input.focus();
await wait(300);
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', keyCode: 40, bubbles: true }));
await wait(500);
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true }));
await wait(300);
}
}
}
// 2. FILE INPUTS (Resume/CV Upload) - SMART: Select existing or upload once
// LinkedIn remembers previously uploaded CVs - we should select those instead of re-uploading
// STEP 2a: First, try to select an existing/previously uploaded resume
let resumeAlreadySelected = false;
// Look for resume selection cards/radio buttons (LinkedIn shows previously uploaded resumes)
const resumeSelectors = [
// Radio buttons for resume selection
'input[type="radio"][name*="resume"]',
'input[type="radio"][name*="cv"]',
'input[type="radio"][id*="resume"]',
'input[type="radio"][id*="document"]',
// Clickable resume cards
'[data-test-document-upload-item]',
'.jobs-document-upload-redesign-card',
'.jobs-document-upload__container',
'.document-upload-item',
// Resume list items
'[class*="resume-card"]',