-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
49 lines (44 loc) · 1.52 KB
/
content.js
File metadata and controls
49 lines (44 loc) · 1.52 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
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === "getContext") {
const selection = window.getSelection();
if (!selection.rangeCount) {
sendResponse({ context: "" });
return;
}
const range = selection.getRangeAt(0);
let container = range.commonAncestorContainer;
if (container.nodeType === Node.TEXT_NODE) {
container = container.parentElement;
}
const blockTags = new Set([
"P", "DIV", "ARTICLE", "SECTION", "LI", "BLOCKQUOTE",
"TD", "TH", "H1", "H2", "H3", "H4", "H5", "H6", "PRE",
]);
let block = container;
while (block && !blockTags.has(block.tagName)) {
block = block.parentElement;
}
const contextText = (block || container).innerText || "";
sendResponse({ context: contextText.slice(0, 2000) });
return;
}
if (msg.type === "getPageContent") {
const content = extractPageContent();
sendResponse({ content });
return;
}
});
function extractPageContent() {
const selectors = ["article", '[role="main"]', "main", ".post-content", ".article-content", ".entry-content"];
for (const sel of selectors) {
const el = document.querySelector(sel);
if (el && el.innerText.trim().length > 200) {
return el.innerText.trim().slice(0, 12000);
}
}
const body = document.body.cloneNode(true);
for (const tag of body.querySelectorAll("nav, header, footer, aside, script, style, .sidebar, .comments")) {
tag.remove();
}
return (body.innerText || "").trim().slice(0, 12000);
}