-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
110 lines (94 loc) · 4.43 KB
/
popup.js
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
document.getElementById('summarizeBtn').addEventListener('click', async () => {
const summaryDiv = document.getElementById('summary');
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab) {
throw new Error("No active tab found");
}
summaryDiv.innerHTML = '<p>Generating summary...</p>';
const [{result}] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => {
function getMainContent() {
// For Wikipedia
if (window.location.hostname.includes('wikipedia.org')) {
const content = document.getElementById('mw-content-text');
if (content) {
// Get only the first few paragraphs
const paragraphs = content.querySelectorAll('p');
let text = '';
let count = 0;
for (let p of paragraphs) {
// Skip empty paragraphs or those with just citations
if (p.textContent.trim().length < 50) continue;
text += p.textContent + ' ';
count++;
if (count >= 3) break; // Only get first 3 substantial paragraphs
}
// Clean up the text
text = text.replace(/\[\d+\]/g, ''); // Remove citations
text = text.replace(/\s+/g, ' ').trim(); // Clean spaces
return text;
}
}
// For other websites
const selectors = [
'main article',
'article',
'[role="main"]',
'#content',
'.content'
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (element) {
// Get only first few paragraphs
const paragraphs = element.querySelectorAll('p');
let text = '';
let count = 0;
for (let p of paragraphs) {
if (p.textContent.trim().length < 50) continue;
text += p.textContent + ' ';
count++;
if (count >= 3) break;
}
return text;
}
}
// Fallback: get first few paragraphs from body
const paragraphs = document.body.querySelectorAll('p');
let text = '';
let count = 0;
for (let p of paragraphs) {
if (p.textContent.trim().length < 50) continue;
text += p.textContent + ' ';
count++;
if (count >= 3) break;
}
return text;
}
const text = getMainContent();
// Limit to 1500 characters
return text.slice(0, 1500);
}
});
if (!result || result.trim().length === 0) {
throw new Error("No text content found on the page");
}
const summaryResponse = await chrome.runtime.sendMessage({
action: "summarize",
text: result
});
if (summaryResponse.error) {
throw new Error(summaryResponse.error);
}
summaryDiv.innerHTML = `
<div style="font-size: 14px; line-height: 1.5;">
${summaryResponse.summary}
</div>
`;
} catch (error) {
summaryDiv.innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
console.error('Error:', error);
}
});