-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentScript.js
More file actions
81 lines (67 loc) · 2.24 KB
/
Copy pathcontentScript.js
File metadata and controls
81 lines (67 loc) · 2.24 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
function safeSendMessage(message) {
try {
chrome.runtime.sendMessage(message, () => {
// Ignore runtime errors like "context invalidated" during reloads
void chrome.runtime.lastError;
});
} catch {
// ignore
}
}
function cleanText(s) {
return (s || "").replace(/\s+/g, " ").replace(/\u00a0/g, " ").trim();
}
function getMetaFromPage() {
const title =
document.querySelector('div[data-cy="question-title"]')?.textContent?.trim() ||
document.querySelector("h1")?.textContent?.trim() ||
document.title?.replace(" - LeetCode", "").trim() ||
"Untitled";
return { title, url: location.href };
}
function findDescriptionRoot() {
// LeetCode markup changes often, so we try multiple options.
return (
document.querySelector('[data-track-load="description_content"]') ||
document.querySelector('[data-cy="question-content"]') ||
document.querySelector('div[data-key="description-content"]') ||
document.querySelector('div[class*="question-content"]') ||
document.querySelector('div[class*="content__"]') ||
null
);
}
function extractProblemText() {
const root = findDescriptionRoot();
const description = cleanText(root?.innerText).slice(0, 8000);
let constraints = "";
const idx = description.toLowerCase().indexOf("constraints:");
if (idx !== -1) constraints = cleanText(description.slice(idx, idx + 1500));
return { description, constraints };
}
function sendAll() {
safeSendMessage({ type: "LC_META", payload: getMetaFromPage() });
safeSendMessage({ type: "LC_PROBLEM_TEXT", payload: extractProblemText() });
}
// Wait for LeetCode to render description, retry for up to ~10s
let attempts = 0;
const maxAttempts = 20;
const interval = setInterval(() => {
attempts += 1;
sendAll();
const root = findDescriptionRoot();
if (root || attempts >= maxAttempts) {
clearInterval(interval);
}
}, 500);
// Debounced mutation observer for SPA updates
let lastUrl = location.href;
let timer = null;
const observer = new MutationObserver(() => {
if (location.href !== lastUrl) lastUrl = location.href;
if (timer) return;
timer = setTimeout(() => {
timer = null;
sendAll();
}, 600);
});
observer.observe(document.documentElement, { subtree: true, childList: true });