-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
230 lines (208 loc) · 9.29 KB
/
Copy pathcontent.js
File metadata and controls
230 lines (208 loc) · 9.29 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
// ApplyPilot — content script
// 1) Detects application forms and shows a floating "Autofill" pill.
// 2) Fills fields from the saved profile using label/name heuristics.
(() => {
if (window.__jobflowInjected) return;
window.__jobflowInjected = true;
// Map profile keys -> matching keywords found in field labels/names/placeholders.
const FIELD_MAP = [
["firstName", ["first name", "firstname", "given name", "fname"]],
["lastName", ["last name", "lastname", "surname", "family name", "lname"]],
["email", ["email", "e-mail"]],
["phone", ["phone", "mobile", "telephone", "tel"]],
["city", ["city", "town"]],
["state", ["state", "province", "region"]],
["country", ["country"]],
["linkedin", ["linkedin"]],
["github", ["github"]],
["portfolio", ["portfolio"]],
["website", ["website", "personal site", "url"]],
["currentTitle", ["current title", "job title", "your title", "position"]],
["currentCompany", ["current company", "employer", "current employer"]],
["salary", ["salary", "compensation", "expected pay"]],
["noticePeriod", ["notice period", "availability", "start date"]],
["workAuth", ["work authorization", "authorized to work", "visa status"]],
["summary", ["summary", "about you", "tell us about"]],
["coverLetter", ["cover letter", "why do you", "motivation", "message"]]
];
const NAME_HINTS = ["name"]; // fallback: full name
const norm = (s) => (s || "").toLowerCase().replace(/\s+/g, " ").trim();
function labelFor(el) {
let text = "";
if (el.id) {
const l = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
if (l) text += " " + l.textContent;
}
const wrap = el.closest("label");
if (wrap) text += " " + wrap.textContent;
// preceding label-ish siblings
const prev = el.previousElementSibling;
if (prev && /label|span|div|p/i.test(prev.tagName)) text += " " + prev.textContent;
text += " " + (el.getAttribute("aria-label") || "");
text += " " + (el.getAttribute("placeholder") || "");
text += " " + (el.getAttribute("name") || "");
text += " " + (el.getAttribute("id") || "");
return norm(text);
}
function setValue(el, value) {
if (value == null || value === "") return false;
const proto = el.tagName === "TEXTAREA"
? window.HTMLTextAreaElement.prototype
: window.HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, "value").set;
setter.call(el, value);
el.dispatchEvent(new Event("input", { bubbles: true }));
el.dispatchEvent(new Event("change", { bubbles: true }));
highlight(el);
return true;
}
function highlight(el) {
el.classList.add("jobflow-filled");
setTimeout(() => el.classList.remove("jobflow-filled"), 2000);
}
async function autofill() {
const { profile = {} } = await chrome.storage.local.get("profile");
const fullName = [profile.firstName, profile.lastName].filter(Boolean).join(" ");
const fields = document.querySelectorAll(
'input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=checkbox]):not([type=radio]):not([type=file]), textarea'
);
let count = 0;
fields.forEach((el) => {
if (el.value && el.value.trim()) return; // don't overwrite
const label = labelFor(el);
if (!label) return;
for (const [key, kws] of FIELD_MAP) {
if (kws.some((k) => label.includes(k))) {
if (setValue(el, profile[key])) count++;
return;
}
}
// full-name fallback (only if it clearly isn't first/last handled above)
if (NAME_HINTS.some((k) => label.includes(k)) && fullName) {
if (setValue(el, fullName)) count++;
}
});
const resumeCount = await attachResume();
// Note: no toast here — the background aggregates counts across all frames
// and sends one AUTOFILL_TOAST to the top frame.
return { count, resumeCount };
}
// ---------- Résumé attachment ----------
// Chrome forbids setting input.value on file inputs, but a real File assigned
// through DataTransfer is allowed — that's what we use here.
function dataUrlToFile(dataUrl, name, type) {
const [meta, b64] = dataUrl.split(",");
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
const mime = type || (meta.match(/:(.*?);/) || [])[1] || "application/octet-stream";
return new File([arr], name || "resume", { type: mime });
}
async function attachResume() {
let resume;
try { ({ resume } = await chrome.storage.local.get("resume")); } catch { return 0; }
if (!resume || !resume.dataUrl) return 0;
let n = 0;
document.querySelectorAll('input[type="file"]').forEach((inp) => {
if (inp.files && inp.files.length) return; // don't replace a chosen file
const label = labelFor(inp);
const accept = (inp.getAttribute("accept") || "").toLowerCase();
const looksResume = /resume|résumé|cv|curriculum|upload|attach/.test(label);
const acceptsDoc = accept && /pdf|word|document|\.docx?|officedocument/.test(accept);
// Attach when the field clearly wants a résumé, or explicitly accepts docs.
// Skip image-only fields (avatars) which never match acceptsDoc.
if (!looksResume && !acceptsDoc) return;
try {
const file = dataUrlToFile(resume.dataUrl, resume.name, resume.type);
const dt = new DataTransfer();
dt.items.add(file);
inp.files = dt.files;
inp.dispatchEvent(new Event("input", { bubbles: true }));
inp.dispatchEvent(new Event("change", { bubbles: true }));
highlight(inp);
n++;
} catch (e) { /* some sites lock file inputs — skip */ }
});
return n;
}
// ---------- Floating UI ----------
let isTopFrame = true;
try { isTopFrame = window === window.top; } catch (e) { isTopFrame = false; }
// Looks like an application form? Prefer real <form>s; otherwise require a few
// inputs plus a strong signal (email/phone/file/textarea) to avoid firing on
// pages that merely have a search box or newsletter field.
function hasApplicationForm() {
const inForm = document.querySelectorAll("form input:not([type=hidden]), form textarea");
if (inForm.length >= 3) return true;
const inputs = document.querySelectorAll("input:not([type=hidden]), textarea");
const signal = document.querySelector(
'input[type=email], input[type=tel], input[type=file], textarea'
);
return inputs.length >= 3 && !!signal;
}
let host;
function mountPill() {
if (host || !isTopFrame) return; // one pill, in the top frame only
host = document.createElement("div");
host.id = "jobflow-pill";
host.innerHTML = `
<button class="jf-fill" title="Autofill with ApplyPilot (Ctrl/Cmd+Shift+U)">
<span class="jf-dot"></span> Autofill
</button>`;
document.documentElement.appendChild(host);
// Ask the background to run autofill in every frame of this tab, then it
// reports one aggregated result back for the toast.
host.querySelector(".jf-fill").addEventListener("click", () => {
chrome.runtime.sendMessage({ type: "AUTOFILL_ALL" }).catch(() => {});
});
}
function toast(msg) {
let t = document.getElementById("jobflow-toast");
if (!t) {
t = document.createElement("div");
t.id = "jobflow-toast";
document.documentElement.appendChild(t);
}
t.textContent = msg;
t.classList.add("show");
clearTimeout(t._timer);
t._timer = setTimeout(() => t.classList.remove("show"), 2400);
}
// Messages from background: AUTOFILL runs in THIS frame and reports its counts;
// AUTOFILL_TOAST / SHOW_PILL are handled by the top frame.
chrome.runtime.onMessage.addListener((msg, _s, sendResponse) => {
if (msg.type === "AUTOFILL") {
autofill().then((r) => sendResponse({ ok: true, ...r }));
return true; // async
}
if (msg.type === "AUTOFILL_TOAST") { toast(msg.msg); }
if (msg.type === "SHOW_PILL") { mountPill(); } // a subframe has a form
});
// Detect a form, then act: top frame mounts the pill; a subframe tells the
// background (which relays SHOW_PILL to the top frame) so iframe-only forms
// still get a pill. Self-disconnects once found or after a timeout so we
// never observe indefinitely.
let observer = null;
function stopObserving() { if (observer) { observer.disconnect(); observer = null; } }
function detectAndAct() {
if (!hasApplicationForm()) return false;
if (isTopFrame) {
mountPill();
} else {
// Notify now and once more shortly after, in case the top frame's message
// listener wasn't ready yet when the iframe finished loading.
const notify = () => chrome.runtime.sendMessage({ type: "FRAME_HAS_FORM" }).catch(() => {});
notify();
setTimeout(notify, 1000);
}
return true;
}
function startDetection() {
if (detectAndAct()) return;
observer = new MutationObserver(() => { if (detectAndAct()) stopObserving(); });
observer.observe(document.documentElement, { childList: true, subtree: true });
setTimeout(stopObserving, 20000); // safety valve for busy SPAs
}
if (document.readyState === "complete" || document.readyState === "interactive") startDetection();
else window.addEventListener("DOMContentLoaded", startDetection, { once: true });
})();