-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
261 lines (217 loc) · 7.26 KB
/
content.js
File metadata and controls
261 lines (217 loc) · 7.26 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Content script for highlighting text on web pages
// Store highlights for this page
let highlights = [];
const HIGHLIGHT_CLASS = 'wiki-notes-highlight';
// Load highlights for current page when script loads
loadHighlights();
// Store last right-clicked element
let lastRightClickedElement = null;
// Track right-click position
document.addEventListener('contextmenu', (e) => {
lastRightClickedElement = e.target;
}, true);
// Listen for messages from background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'highlightText') {
highlightSelection(request.text, request.color || 'yellow');
sendResponse({ success: true });
} else if (request.action === 'getHighlights') {
sendResponse({ highlights: highlights });
} else if (request.action === 'clearHighlights') {
clearAllHighlights();
sendResponse({ success: true });
} else if (request.action === 'removeHighlightAtClick') {
removeHighlightAtElement(lastRightClickedElement);
sendResponse({ success: true });
}
return true;
});
// Highlight currently selected text
function highlightSelection(textToFind, color = 'yellow') {
const selection = window.getSelection();
if (!selection.rangeCount || selection.isCollapsed) {
console.log('No valid selection found');
return;
}
const range = selection.getRangeAt(0);
const selectedText = textToFind || selection.toString();
if (!selectedText || selectedText.trim().length === 0) {
console.log('No text selected');
return;
}
// Create highlight span with color class
const highlightSpan = document.createElement('span');
highlightSpan.className = `${HIGHLIGHT_CLASS} highlight-${color}`;
const highlightId = Date.now().toString();
highlightSpan.setAttribute('data-highlight-id', highlightId);
highlightSpan.setAttribute('data-highlight-color', color);
// Wrap the selected content
try {
range.surroundContents(highlightSpan);
} catch (e) {
// If surroundContents fails (complex selection), use different approach
try {
const fragment = range.extractContents();
highlightSpan.appendChild(fragment);
range.insertNode(highlightSpan);
} catch (err) {
console.error('Failed to highlight:', err);
return;
}
}
// Save highlight info
const highlightInfo = {
id: highlightId,
text: selectedText.trim(),
timestamp: Date.now(),
color: color
};
highlights.push(highlightInfo);
saveHighlights();
// Clear selection
selection.removeAllRanges();
console.log('Highlighted:', selectedText, 'with color:', color);
}
// Get XPath for an element (for persistence)
function getXPath(element) {
if (element.id !== '') {
return 'id("' + element.id + '")';
}
if (element === document.body) {
return element.tagName;
}
let ix = 0;
const siblings = element.parentNode.childNodes;
for (let i = 0; i < siblings.length; i++) {
const sibling = siblings[i];
if (sibling === element) {
return getXPath(element.parentNode) + '/' + element.tagName + '[' + (ix + 1) + ']';
}
if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {
ix++;
}
}
}
// Get element by XPath
function getElementByXPath(xpath) {
return document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
// Save highlights to storage
function saveHighlights() {
const pageUrl = window.location.href;
const storageKey = `highlights_${hashCode(pageUrl)}`;
chrome.storage.local.get(['allHighlights'], (result) => {
const allHighlights = result.allHighlights || {};
allHighlights[pageUrl] = highlights;
chrome.storage.local.set({ allHighlights: allHighlights });
});
}
// Load highlights for current page
function loadHighlights() {
const pageUrl = window.location.href;
chrome.storage.local.get(['allHighlights'], (result) => {
const allHighlights = result.allHighlights || {};
highlights = allHighlights[pageUrl] || [];
// Restore highlights on page
restoreHighlights();
});
}
// Restore highlights on the page
function restoreHighlights() {
highlights.forEach(highlight => {
try {
// Try to find text nodes containing the highlighted text
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
null,
false
);
let node;
while (node = walker.nextNode()) {
const text = node.textContent;
if (text.includes(highlight.text) && !node.parentElement.classList.contains(HIGHLIGHT_CLASS)) {
const index = text.indexOf(highlight.text);
if (index !== -1) {
const range = document.createRange();
range.setStart(node, index);
range.setEnd(node, index + highlight.text.length);
const span = document.createElement('span');
const color = highlight.color || 'yellow';
span.className = `${HIGHLIGHT_CLASS} highlight-${color}`;
span.setAttribute('data-highlight-id', highlight.id);
span.setAttribute('data-highlight-color', color);
range.surroundContents(span);
break;
}
}
}
} catch (e) {
console.log('Could not restore highlight:', e);
}
});
}
// Clear all highlights
function clearAllHighlights() {
const highlightElements = document.querySelectorAll('.' + HIGHLIGHT_CLASS);
highlightElements.forEach(el => {
const parent = el.parentNode;
while (el.firstChild) {
parent.insertBefore(el.firstChild, el);
}
parent.removeChild(el);
});
highlights = [];
saveHighlights();
}
// Simple hash function for URLs
function hashCode(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return Math.abs(hash).toString(36);
}
// Remove highlight from specific element
function removeHighlightAtElement(element) {
if (!element) return;
// Check if the element itself is highlighted
if (element.classList.contains(HIGHLIGHT_CLASS)) {
removeHighlightElement(element);
return;
}
// Check if any parent is highlighted (in case clicked on child element)
let current = element;
while (current && current !== document.body) {
if (current.classList && current.classList.contains(HIGHLIGHT_CLASS)) {
removeHighlightElement(current);
return;
}
current = current.parentNode;
}
console.log('No highlight found at clicked position');
}
// Helper function to remove a highlight element
function removeHighlightElement(element) {
const highlightId = element.getAttribute('data-highlight-id');
// Remove from DOM
const parent = element.parentNode;
while (element.firstChild) {
parent.insertBefore(element.firstChild, element);
}
parent.removeChild(element);
// Remove from storage
highlights = highlights.filter(h => h.id !== highlightId);
saveHighlights();
console.log('Highlight removed:', highlightId);
}
// Allow clicking highlighted text to remove it (legacy - keep for Alt/Ctrl+Click)
document.addEventListener('click', (e) => {
if (e.target.classList.contains(HIGHLIGHT_CLASS)) {
if (e.altKey || e.ctrlKey) { // Hold Alt or Ctrl and click to remove
removeHighlightElement(e.target);
}
}
});