-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
83 lines (66 loc) · 2.3 KB
/
content.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
console.log('Content script loaded!');
// Initialize the highlighting functionality
let isEnabled = false;
// Create message passing channel between popup and content script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "toggle") {
isEnabled = isEnabled ^ true;
console.log('Toggle action received:' + isEnabled);
}
if (request.action === "download") {
console.log("calling download");
downloadHighlights();
}
});
// Handle text selection
document.addEventListener('mouseup', () => {
if (!isEnabled) return;
const selection = window.getSelection();
const selectedText = selection.toString().trim();
if (selectedText) {
console.log(selectedText);
const range = selection.getRangeAt(0);
const span = document.createElement('span');
span.className = 'yellow-highlight';
span.textContent = selectedText;
range.deleteContents();
range.insertNode(span);
// Save highlight
saveHighlight(selectedText);
}
});
// Save highlight to localStorage
function saveHighlight(text) {
const highlights = JSON.parse(localStorage.getItem('highlights') || '{}');
const url = window.location.href;
if (!highlights[url]) {
highlights[url] = [];
}
highlights[url].push(text);
localStorage.setItem('highlights', JSON.stringify(highlights));
}
// Download highlights
function downloadHighlights() {
const highlights = JSON.parse(localStorage.getItem('highlights') || '{}');
const url = window.location.href;
const pageHighlights = highlights[url] || [];
let content = `URL: ${url}\n\nHighlights:\n`;
pageHighlights.forEach((text, index) => {
content += `${index + 1}. ${text}\n`;
});
const blob = new Blob([content], { type: 'text/plain' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'highlights.txt';
a.click();
cleanLocalStorage();
}
function cleanLocalStorage() {
const highlights = JSON.parse(localStorage.getItem('highlights') || '{}');
const url = window.location.href;
if (!highlights[url]) {
highlights[url] = [];
}
highlights[url] = [];
localStorage.setItem('highlights', JSON.stringify(highlights));
}