-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
193 lines (178 loc) · 7.1 KB
/
Copy pathbackground.js
File metadata and controls
193 lines (178 loc) · 7.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// ApplyPilot — background service worker (MV3)
// Handles: context menus, keyboard commands, badge counts, install defaults.
// ---------- Install / defaults ----------
chrome.runtime.onInstalled.addListener(async (details) => {
const { profile, jobs } = await chrome.storage.local.get(["profile", "jobs"]);
if (!profile) {
await chrome.storage.local.set({
profile: {
firstName: "", lastName: "", email: "", phone: "",
city: "", state: "", country: "", linkedin: "", github: "",
portfolio: "", website: "", currentTitle: "", currentCompany: "",
workAuth: "", requiresSponsorship: "no", salary: "", noticePeriod: "",
coverLetter: "", summary: ""
}
});
}
if (!jobs) await chrome.storage.local.set({ jobs: [] });
// removeAll first so re-running onInstalled (e.g. on update) can't throw a
// "duplicate id" error.
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({
id: "jobflow-capture",
title: "ApplyPilot: Save this job",
contexts: ["page", "link", "selection"]
});
});
updateBadge();
// First-run onboarding: open the profile page so new users set up before use.
if (details && details.reason === "install") {
chrome.storage.local.set({ onboarded: false });
chrome.runtime.openOptionsPage();
}
});
// ---------- Context menu ----------
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "jobflow-capture") captureJob(tab);
});
// ---------- Keyboard commands ----------
chrome.commands.onCommand.addListener(async (command) => {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab) return;
if (command === "capture-job") captureJob(tab);
if (command === "autofill") runAutofill(tab.id);
});
// Run autofill in EVERY frame of a tab, sum the results, and send one toast to
// the top frame. Needed because application forms are often inside iframes.
async function runAutofill(tabId) {
let frames;
try { frames = await chrome.webNavigation.getAllFrames({ tabId }); }
catch { frames = [{ frameId: 0 }]; }
if (!frames || !frames.length) frames = [{ frameId: 0 }];
let count = 0, resume = 0;
await Promise.all(frames.map(async (f) => {
try {
const r = await chrome.tabs.sendMessage(tabId, { type: "AUTOFILL" }, { frameId: f.frameId });
if (r) { count += r.count || 0; resume += r.resumeCount || 0; }
} catch (e) { /* frame has no content script (e.g. about:blank) — skip */ }
}));
let msg;
if (!count && !resume) msg = "No matching fields found";
else {
const parts = [];
if (count) parts.push(`${count} field${count > 1 ? "s" : ""}`);
if (resume) parts.push("résumé attached");
msg = "Filled " + parts.join(" · ");
}
chrome.tabs.sendMessage(tabId, { type: "AUTOFILL_TOAST", msg }, { frameId: 0 }).catch(() => {});
}
// ---------- Message router (popup / content) ----------
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === "CAPTURE_FROM_POPUP") {
chrome.tabs.query({ active: true, currentWindow: true }).then(([tab]) => {
captureJob(tab).then((job) => sendResponse({ ok: true, job }));
});
return true; // async
}
if (msg.type === "AUTOFILL_ALL" && sender.tab) {
runAutofill(sender.tab.id);
}
// A subframe found an application form — ask the top frame to show the pill.
if (msg.type === "FRAME_HAS_FORM" && sender.tab) {
chrome.tabs.sendMessage(sender.tab.id, { type: "SHOW_PILL" }, { frameId: 0 }).catch(() => {});
}
if (msg.type === "JOBS_CHANGED") updateBadge();
});
// ---------- Capture logic ----------
async function captureJob(tab) {
if (!tab || !tab.id) return null;
let scraped = { title: tab.title || "", company: "", location: "", description: "" };
try {
const [res] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: scrapePosting
});
if (res && res.result) scraped = { ...scraped, ...res.result };
} catch (e) { /* restricted page — fall back to tab title */ }
const job = {
id: crypto.randomUUID(),
title: cleanTitle(scraped.title),
company: (scraped.company || domainFrom(tab.url) || "").replace(/\s+/g, " ").trim().slice(0, 80),
location: (scraped.location || "").replace(/\s+/g, " ").trim().slice(0, 80),
description: (scraped.description || "").slice(0, 1200),
url: tab.url,
stage: "saved",
notes: "",
createdAt: Date.now(),
updatedAt: Date.now()
};
const { jobs = [] } = await chrome.storage.local.get("jobs");
// avoid dupes by URL
if (!jobs.some((j) => j.url === job.url)) {
jobs.unshift(job);
await chrome.storage.local.set({ jobs });
updateBadge();
flashBadge("+1");
} else {
flashBadge("✓");
}
return job;
}
// Runs in the page context — best-effort structured scraping.
function scrapePosting() {
const pick = (sels) => {
for (const s of sels) {
const el = document.querySelector(s);
if (!el) continue;
// <meta> carries its value in the content attribute, not textContent.
const val = el.tagName === "META" ? (el.getAttribute("content") || "") : el.textContent;
if (val && val.trim()) return val.trim();
}
return "";
};
// JSON-LD JobPosting is the most reliable source.
let ld = {};
for (const node of document.querySelectorAll('script[type="application/ld+json"]')) {
try {
const data = JSON.parse(node.textContent);
const arr = Array.isArray(data) ? data : [data];
const jp = arr.find((d) => d && (d["@type"] === "JobPosting"));
if (jp) { ld = jp; break; }
} catch (e) {}
}
const company =
(ld.hiringOrganization && (ld.hiringOrganization.name || ld.hiringOrganization)) ||
pick(['[data-company]', '.company', '[class*="company"]', 'meta[property="og:site_name"]']);
const location =
(ld.jobLocation && ld.jobLocation.address &&
[ld.jobLocation.address.addressLocality, ld.jobLocation.address.addressRegion]
.filter(Boolean).join(", ")) ||
pick(['[class*="location"]', '[data-location]']);
return {
title: ld.title || pick(["h1", '[class*="title"]']) || document.title,
company: typeof company === "string" ? company : "",
location: typeof location === "string" ? location : "",
description: (ld.description || pick(["article", "main", '[class*="description"]']) || "")
.replace(/\s+/g, " ").trim()
};
}
// ---------- Helpers ----------
function cleanTitle(t) {
return (t || "").split(/[|\-–—]/)[0].trim().slice(0, 120) || "Untitled role";
}
function domainFrom(url) {
try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return ""; }
}
async function updateBadge() {
const { jobs = [] } = await chrome.storage.local.get("jobs");
const active = jobs.filter((j) => j.stage !== "rejected").length;
chrome.action.setBadgeBackgroundColor({ color: "#059669" });
chrome.action.setBadgeText({ text: active ? String(active) : "" });
}
let flashTimer;
function flashBadge(text) {
chrome.action.setBadgeBackgroundColor({ color: "#16a34a" });
chrome.action.setBadgeText({ text });
clearTimeout(flashTimer);
flashTimer = setTimeout(updateBadge, 1500);
}