-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
390 lines (338 loc) · 15.2 KB
/
Copy pathcontent.js
File metadata and controls
390 lines (338 loc) · 15.2 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
// LinkedIn Applicant Exporter - Content Script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
try {
if (message.action === 'getApplicantCount') {
const cards = document.querySelectorAll('.hiring-applicants__list-item');
sendResponse({ count: cards.length });
return;
}
if (message.action === 'exportApplicants') {
exportApplicants(message.type)
.then(result => sendResponse(result))
.catch(error => sendResponse({ success: false, error: error.message }));
return true; // Keep message channel open for async response
}
} catch (error) {
console.error('Content script error:', error);
sendResponse({ success: false, error: error.message });
}
});
async function exportApplicants(type) {
try {
let allApplicants = [];
let currentPage = 1;
let totalPages = 1;
const startMessage = `🚀 Starting multi-page extraction...`;
console.log(startMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: startMessage
});
// Process all pages
while (currentPage <= totalPages) {
const pageMessage = `📄 Processing page ${currentPage}...`;
console.log(pageMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: pageMessage
});
// Get current page applicants
let cards = document.querySelectorAll('.hiring-applicants__list-item');
if (cards.length === 0 && currentPage === 1) {
throw new Error('No applicants found on this page');
}
const foundMessage = `Found ${cards.length} applicant cards on page ${currentPage}`;
console.log(foundMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: foundMessage
});
// Extract basic info from current page cards
let pageApplicants = [];
cards.forEach((card, index) => {
try {
const name = card.querySelector('.hiring-people-card__title')?.textContent?.trim() || 'N/A';
const title = card.querySelector('.artdeco-entity-lockup__metadata:first-of-type')?.textContent?.trim() || 'N/A';
const location = card.querySelector('.artdeco-entity-lockup__metadata:nth-of-type(2)')?.textContent?.trim() || 'N/A';
const experienceElements = card.querySelectorAll('.artdeco-entity-lockup__caption ul li');
let experience = '';
experienceElements.forEach(exp => {
const expText = exp.querySelector('div span')?.textContent?.trim();
if (expText) experience += expText + '; ';
});
experience = experience.slice(0, -2);
const appliedTime = card.querySelector('.hiring-applicant-insights__separator')?.textContent?.trim() || 'N/A';
const qualifications = card.querySelector('.hiring-applicant-insights__separator + div span')?.textContent?.trim() || 'N/A';
const detailLink = card.querySelector('a')?.href || 'N/A';
pageApplicants.push({
name, title, location, experience,
applied_time: appliedTime,
qualifications,
detail_link: detailLink,
linkedin_profile: 'N/A',
cardElement: card,
page: currentPage
});
} catch (e) {
console.error(`Error processing applicant ${index + 1} on page ${currentPage}:`, e);
}
});
// If enhanced export, get LinkedIn profiles for current page
if (type === 'enhanced') {
const profileMessage = `Getting LinkedIn profiles for ${pageApplicants.length} applicants on page ${currentPage}...`;
console.log(profileMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: profileMessage
});
for (let i = 0; i < pageApplicants.length; i++) {
// Send progress update
chrome.runtime.sendMessage({
action: 'updateProgress',
current: allApplicants.length + i,
total: allApplicants.length + pageApplicants.length
});
const processingMessage = `Processing ${allApplicants.length + i + 1}: ${pageApplicants[i].name} (Page ${currentPage})`;
console.log(processingMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: processingMessage
});
await getLinkedInProfile(pageApplicants, i);
}
}
// Add current page applicants to total
allApplicants = allApplicants.concat(pageApplicants);
// Get total pages from pagination if available
const paginationButtons = document.querySelectorAll('button[aria-label*="Page"]');
if (paginationButtons.length > 0) {
const pageNumbers = Array.from(paginationButtons).map(btn => {
const ariaLabel = btn.getAttribute('aria-label');
const match = ariaLabel?.match(/Page (\d+)/);
return match ? parseInt(match[1]) : 0;
}).filter(num => num > 0);
if (pageNumbers.length > 0) {
totalPages = Math.max(...pageNumbers);
}
console.log(`Detected total pages: ${totalPages} from buttons:`, pageNumbers);
chrome.runtime.sendMessage({
action: 'logMessage',
message: `Detected total pages: ${totalPages}`
});
}
const logMessage = `📊 Page ${currentPage}/${totalPages} complete. Total candidates so far: ${allApplicants.length}`;
console.log(logMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: logMessage
});
// Look for the specific next page button using aria-label
let nextButton = null;
const nextPageNumber = currentPage + 1;
// First try to find the specific next page button
const nextPageSelector = `button[aria-label="Page ${nextPageNumber}"]`;
nextButton = document.querySelector(nextPageSelector);
console.log(`Looking for button with aria-label="Page ${nextPageNumber}"`);
console.log('Available pagination buttons:', Array.from(document.querySelectorAll('button[aria-label*="Page"]')).map(btn => ({
ariaLabel: btn.getAttribute('aria-label'),
text: btn.textContent?.trim(),
disabled: btn.disabled,
ariaCurrent: btn.getAttribute('aria-current')
})));
// If specific page button not found, fall back to generic next selectors
if (!nextButton) {
console.log(`Page ${nextPageNumber} button not found, trying generic next selectors...`);
const fallbackSelectors = [
'button[aria-label*="Next"]:not([disabled])',
'button[aria-label*="next"]:not([disabled])',
'.artdeco-pagination__button--next:not([disabled])'
];
for (const selector of fallbackSelectors) {
const button = document.querySelector(selector);
if (button && !button.disabled) {
nextButton = button;
console.log(`Found fallback next button with selector: ${selector}`);
break;
}
}
} else {
console.log(`✅ Found next page button: Page ${nextPageNumber}`);
}
// If there's a next page and we haven't reached the total, go to next page
if (nextButton && currentPage < totalPages) {
const nextLogMessage = `➡️ Going to page ${currentPage + 1}...`;
console.log(nextLogMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: nextLogMessage
});
// Try multiple click methods to ensure it works
console.log('Attempting to click next page button...');
try {
// Method 1: Regular click
nextButton.click();
// Method 2: Dispatch click event (backup)
nextButton.dispatchEvent(new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
}));
// Method 3: Focus and trigger (backup)
nextButton.focus();
nextButton.dispatchEvent(new KeyboardEvent('keydown', {
key: 'Enter',
bubbles: true
}));
console.log('✅ Click methods executed');
} catch (clickError) {
console.error('❌ Error clicking next button:', clickError);
chrome.runtime.sendMessage({
action: 'logMessage',
message: `❌ Failed to click next page button: ${clickError.message}`
});
}
// Wait longer for new page to load and check if it worked
console.log('⏳ Waiting for page to load...');
chrome.runtime.sendMessage({
action: 'logMessage',
message: '⏳ Waiting for page to load...'
});
await new Promise(resolve => setTimeout(resolve, 5000));
// Verify we're on the new page
const currentPageButton = document.querySelector(`button[aria-current="true"][aria-label*="Page"]`);
console.log('Current page button after click:', currentPageButton?.getAttribute('aria-label'));
const actualCurrentPage = currentPageButton ?
parseInt(currentPageButton.getAttribute('aria-label').match(/Page (\d+)/)?.[1] || '1') :
currentPage;
console.log(`Expected page: ${currentPage + 1}, Actual page: ${actualCurrentPage}`);
chrome.runtime.sendMessage({
action: 'logMessage',
message: `Expected page: ${currentPage + 1}, Actual page: ${actualCurrentPage}`
});
if (actualCurrentPage === currentPage + 1) {
console.log(`✅ Successfully navigated to page ${actualCurrentPage}`);
chrome.runtime.sendMessage({
action: 'logMessage',
message: `✅ Successfully navigated to page ${actualCurrentPage}`
});
currentPage = actualCurrentPage; // Update to the actual page
} else if (actualCurrentPage > currentPage) {
// We moved forward but maybe not to the expected page
console.log(`✅ Moved to page ${actualCurrentPage} (expected ${currentPage + 1})`);
chrome.runtime.sendMessage({
action: 'logMessage',
message: `✅ Moved to page ${actualCurrentPage} (expected ${currentPage + 1})`
});
currentPage = actualCurrentPage;
} else {
console.log(`❌ Still on page ${actualCurrentPage}, navigation may have failed`);
chrome.runtime.sendMessage({
action: 'logMessage',
message: `❌ Navigation failed, still on page ${actualCurrentPage}`
});
// Stop if we're stuck on the same page
break;
}
} else {
const endLogMessage = `🏁 Reached end. No more pages or next button disabled.`;
console.log(endLogMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: endLogMessage
});
break;
}
}
// Clean up cardElement before CSV export
allApplicants.forEach(app => delete app.cardElement);
// Generate CSV
const csvHeaders = type === 'enhanced'
? 'Name,Title,Location,Experience,Applied Time,Qualifications,Hiring Detail Link,LinkedIn Profile,Page\n'
: 'Name,Title,Location,Experience,Applied Time,Qualifications,Hiring Detail Link,Page\n';
let csv = csvHeaders;
allApplicants.forEach(app => {
if (type === 'enhanced') {
csv += `"${app.name}","${app.title}","${app.location}","${app.experience}","${app.applied_time}","${app.qualifications}","${app.detail_link}","${app.linkedin_profile}","${app.page}"\n`;
} else {
csv += `"${app.name}","${app.title}","${app.location}","${app.experience}","${app.applied_time}","${app.qualifications}","${app.detail_link}","${app.page}"\n`;
}
});
// Download CSV
const blob = new Blob([csv], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = type === 'enhanced'
? `linkedin-applicants-with-profiles-${totalPages}pages.csv`
: `linkedin-applicants-basic-${totalPages}pages.csv`;
a.click();
window.URL.revokeObjectURL(url);
console.log(`🎉 Done! Extracted ${allApplicants.length} applicants from ${totalPages} pages and downloaded CSV`);
return { success: true, count: allApplicants.length, pages: totalPages };
} catch (error) {
console.error('Export error:', error);
throw error;
}
}
async function getLinkedInProfile(applicants, applicantIndex) {
return new Promise((resolve) => {
try {
const card = applicants[applicantIndex].cardElement;
// Find the clickable link within the card (usually the name link)
const clickableLink = card.querySelector('a') || card.querySelector('.hiring-people-card__title a') || card;
console.log(`🖱️ Clicking on ${applicants[applicantIndex].name}...`);
// Click on the applicant card to open detail panel
clickableLink.click();
// Wait for detail panel to load, then look for "See full profile" link
setTimeout(() => {
try {
const lookingMessage = `🔍 Looking for profile link for ${applicants[applicantIndex].name}...`;
console.log(lookingMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: lookingMessage
});
// Look for all links containing /in/ and log them
const allInLinks = document.querySelectorAll('a[href*="/in/"]');
console.log(`Found ${allInLinks.length} links with /in/:`, Array.from(allInLinks).map(link => ({
text: link.textContent?.trim(),
href: link.href
})));
const seeFullProfileLink = document.querySelector('a[href*="/in/"]');
if (seeFullProfileLink) {
let href = seeFullProfileLink.href;
// Convert relative URLs to absolute URLs if needed
if (href.startsWith('/in/')) {
href = 'https://www.linkedin.com' + href;
}
applicants[applicantIndex].linkedin_profile = href;
const successMessage = `✅ ${applicants[applicantIndex].name}: ${href}`;
console.log(successMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: successMessage
});
} else {
const failMessage = `❌ ${applicants[applicantIndex].name}: No LinkedIn profile found`;
console.log(failMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: failMessage
});
}
} catch (e) {
const errorMessage = `❌ ${applicants[applicantIndex].name}: Error getting profile - ${e.message}`;
console.log(errorMessage);
chrome.runtime.sendMessage({
action: 'logMessage',
message: errorMessage
});
}
resolve();
}, 3000); // Increased to 3 seconds to give more time for detail panel
} catch (e) {
console.error(`Error clicking applicant ${applicantIndex}:`, e);
resolve();
}
});
}