-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
698 lines (605 loc) · 19.7 KB
/
content.js
File metadata and controls
698 lines (605 loc) · 19.7 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
let speechSynthesis = window.speechSynthesis;
let currentUtterance = null;
let isReading = false;
let hoverTimeout = null;
let readingQueue = [];
let currentReadingIndex = 0;
let isMainFrame = window === window.top;
let isLongReading = false; // Track if we're doing a long read (right-click)
let lastHoverText = ''; // Track last hovered text to prevent repeats
// Configuration
const HOVER_DELAY = 300; // milliseconds before reading on hover
const STOP_ON_MOUSE_MOVE = false; // Changed to false to reduce interruptions
// Initialize speech synthesis
function initializeSpeech() {
if (!speechSynthesis) {
console.error('Speech synthesis not supported');
return false;
}
return true;
}
// Stop current speech
function stopSpeech() {
if (speechSynthesis.speaking) {
speechSynthesis.cancel();
}
if (currentUtterance) {
currentUtterance = null;
}
isReading = false;
isLongReading = false;
readingQueue = [];
currentReadingIndex = 0;
lastHoverText = '';
// Clear any pending hover timeout
if (hoverTimeout) {
clearTimeout(hoverTimeout);
hoverTimeout = null;
}
// Notify all frames to stop reading
if (isMainFrame) {
broadcastToAllFrames({ action: 'stopReading' });
}
}
// Speak text using Web Speech API
function speakText(text, isLongRead = false) {
if (!text || text.trim().length === 0) return;
// Don't interrupt long reading with hover
if (isLongReading && !isLongRead) {
return;
}
// Only stop previous speech if we're not in the middle of a queue
if (readingQueue.length === 0 || isLongRead) {
if (speechSynthesis.speaking) {
speechSynthesis.cancel();
}
}
currentUtterance = new SpeechSynthesisUtterance(text);
currentUtterance.rate = 1.0;
currentUtterance.pitch = 1.0;
currentUtterance.volume = 1.0;
currentUtterance.onstart = () => {
isReading = true;
if (isLongRead) {
isLongReading = true;
}
};
currentUtterance.onend = () => {
isReading = false;
currentUtterance = null;
// Check if there are more items in the reading queue
processNextInQueue();
};
currentUtterance.onerror = (event) => {
// Only log errors that aren't interruptions from our own code
if (event.error !== 'interrupted' || readingQueue.length === 0) {
console.error('Speech synthesis error:', event.error);
}
isReading = false;
currentUtterance = null;
// Continue with queue if available
if (readingQueue.length > 0) {
processNextInQueue();
} else {
isLongReading = false;
}
};
try {
speechSynthesis.speak(currentUtterance);
} catch (error) {
console.warn('Speech synthesis blocked:', error.message);
}
}
// Process next item in reading queue
function processNextInQueue() {
currentReadingIndex++;
if (currentReadingIndex < readingQueue.length) {
const nextItem = readingQueue[currentReadingIndex];
speakText(nextItem.text, true); // Mark as long read
} else {
// Queue finished, reset
readingQueue = [];
currentReadingIndex = 0;
isLongReading = false;
}
}
// Add text to reading queue
function queueTextForReading(textArray) {
readingQueue = textArray.map(item => ({ text: item }));
currentReadingIndex = 0;
isLongReading = true;
if (readingQueue.length > 0) {
speakText(readingQueue[0].text, true); // Mark as long read
}
}
// Get text content from element, handling various element types
function getElementText(element) {
if (!element) return '';
// Handle input elements
if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
return element.value || element.placeholder || '';
}
// Handle images with alt text
if (element.tagName === 'IMG') {
return element.alt || element.title || '';
}
// Handle links
if (element.tagName === 'A') {
return element.textContent || element.title || element.href || '';
}
// Get text content, fallback to innerText
return element.textContent || element.innerText || '';
}
// Get text under mouse cursor
function getTextUnderMouse(event) {
const element = document.elementFromPoint(event.clientX, event.clientY);
if (!element) return '';
const text = getElementText(element);
return text.trim();
}
// Get all text from current position to end of page, including iframes
function getTextFromPositionToEnd(startElement) {
if (!startElement) return '';
// Create a tree walker that includes both text nodes and iframe elements
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
{
acceptNode: function(node) {
// Accept iframe elements
if (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'IFRAME') {
return NodeFilter.FILTER_ACCEPT;
}
// Accept text nodes (but skip script and style)
if (node.nodeType === Node.TEXT_NODE) {
const parent = node.parentElement;
if (parent && (parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE')) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
}
}
);
let nodes = [];
let node;
// Collect all nodes in document order
while (node = walker.nextNode()) {
nodes.push(node);
}
// Find the starting position
let startIndex = -1;
for (let i = 0; i < nodes.length; i++) {
const currentNode = nodes[i];
if (currentNode.nodeType === Node.TEXT_NODE) {
if (currentNode.parentElement === startElement ||
startElement.contains(currentNode)) {
startIndex = i;
break;
}
}
}
// If we couldn't find the start position, try to find it by position
if (startIndex === -1) {
const startRect = startElement.getBoundingClientRect();
for (let i = 0; i < nodes.length; i++) {
const currentNode = nodes[i];
if (currentNode.nodeType === Node.TEXT_NODE) {
const range = document.createRange();
range.selectNode(currentNode);
const nodeRect = range.getBoundingClientRect();
if (nodeRect.top >= startRect.top && nodeRect.left >= startRect.left) {
startIndex = i;
break;
}
}
}
}
if (startIndex === -1) {
// Fallback to just the element's text
return getElementText(startElement);
}
// Process nodes from start position to end
const textParts = [];
for (let i = startIndex; i < nodes.length; i++) {
const currentNode = nodes[i];
if (currentNode.nodeType === Node.TEXT_NODE) {
const text = currentNode.textContent.trim();
if (text) {
textParts.push(text);
}
} else if (currentNode.nodeType === Node.ELEMENT_NODE && currentNode.tagName === 'IFRAME') {
// Try to get iframe content
try {
const iframeText = getTextFromIframe(currentNode);
if (iframeText) {
textParts.push(iframeText);
}
} catch (e) {
// Cross-origin iframe, we'll handle this separately
console.log('Cross-origin iframe detected, will handle with postMessage');
}
}
}
return textParts.join(' ').replace(/\s+/g, ' ').trim();
}
// Get text from current frame only
function getTextFromCurrentFrame(startElement) {
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
{
acceptNode: function(node) {
// Skip script and style elements
const parent = node.parentElement;
if (parent && (parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE')) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);
let textNodes = [];
let node;
let foundStart = false;
// Find all text nodes
while (node = walker.nextNode()) {
textNodes.push(node);
}
// Find starting position
for (let i = 0; i < textNodes.length; i++) {
if (textNodes[i].parentElement === startElement ||
startElement.contains(textNodes[i])) {
foundStart = true;
textNodes = textNodes.slice(i);
break;
}
}
if (!foundStart) {
// If we can't find the exact start, just use all text from the element
return getElementText(startElement);
}
// Combine all text from start position to end of current frame
return textNodes
.map(node => node.textContent)
.join(' ')
.replace(/\s+/g, ' ')
.trim();
}
// Get all iframes that appear after the given element
function getAllIframesAfterElement(startElement) {
const iframes = Array.from(document.querySelectorAll('iframe'));
const startRect = startElement.getBoundingClientRect();
return iframes.filter(iframe => {
const iframeRect = iframe.getBoundingClientRect();
// Include iframes that appear after the start element (by document order or position)
return (
iframeRect.top > startRect.top ||
(iframeRect.top === startRect.top && iframeRect.left >= startRect.left)
);
});
}
// Get text from iframe (same-origin only)
function getTextFromIframe(iframe) {
try {
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
if (!iframeDoc || !iframeDoc.body) return '';
const walker = document.createTreeWalker(
iframeDoc.body,
NodeFilter.SHOW_TEXT,
{
acceptNode: function(node) {
const parent = node.parentElement;
if (parent && (parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE')) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);
let textNodes = [];
let node;
while (node = walker.nextNode()) {
textNodes.push(node);
}
return textNodes
.map(node => node.textContent)
.join(' ')
.replace(/\s+/g, ' ')
.trim();
} catch (e) {
// Cross-origin iframe
return '';
}
}
// Mouse move handler for hover reading
function handleMouseMove(event) {
// Don't interrupt long reading (right-click reading)
if (isLongReading) {
return;
}
// Clear existing timeout
if (hoverTimeout) {
clearTimeout(hoverTimeout);
}
// Set new timeout for hover reading
hoverTimeout = setTimeout(() => {
// Double-check we're not in long reading mode
if (isLongReading) {
return;
}
const text = getTextUnderMouse(event);
if (text && text.length > 0 && text !== lastHoverText) {
lastHoverText = text;
speakText(text, false); // Mark as hover read
}
}, HOVER_DELAY);
}
// Right-click handler for reading from cursor to end
function handleContextMenu(event) {
// Get the clicked element
const clickedElement = document.elementFromPoint(event.clientX, event.clientY);
if (clickedElement) {
// Prevent the default context menu
event.preventDefault();
// Start reading from this position
handleReadFromCursorToEnd(clickedElement)
.then(result => {
if (!result.success) {
console.error('Failed to read text:', result.error);
}
})
.catch(error => {
console.error('Error reading text:', error);
});
}
}
// Broadcast message to all frames
function broadcastToAllFrames(message) {
const iframes = document.querySelectorAll('iframe');
for (const iframe of iframes) {
try {
if (iframe.contentWindow) {
iframe.contentWindow.postMessage(message, '*');
}
} catch (e) {
// Cross-origin iframe, can't send message
console.log('Could not send message to iframe:', e.message);
}
}
}
// Handle cross-frame messages
function handleFrameMessage(event) {
if (event.data && event.data.action) {
switch (event.data.action) {
case 'stopReading':
stopSpeech();
break;
case 'getIframeText':
// Respond with iframe text content
const text = document.body ? document.body.innerText || document.body.textContent || '' : '';
event.source.postMessage({
action: 'iframeTextResponse',
text: text.trim(),
frameId: event.data.frameId
}, '*');
break;
}
}
}
// Get text from cross-origin iframes using postMessage
async function getTextFromCrossOriginIframes(startElement) {
const iframes = getAllIframesAfterElement(startElement);
const textPromises = [];
for (let i = 0; i < iframes.length; i++) {
const iframe = iframes[i];
const frameId = `frame_${i}_${Date.now()}`;
const promise = new Promise((resolve) => {
const timeout = setTimeout(() => {
resolve(''); // Timeout after 2 seconds
}, 2000);
const messageHandler = (event) => {
if (event.data && event.data.action === 'iframeTextResponse' && event.data.frameId === frameId) {
clearTimeout(timeout);
window.removeEventListener('message', messageHandler);
resolve(event.data.text || '');
}
};
window.addEventListener('message', messageHandler);
try {
iframe.contentWindow.postMessage({
action: 'getIframeText',
frameId: frameId
}, '*');
} catch (e) {
clearTimeout(timeout);
window.removeEventListener('message', messageHandler);
resolve('');
}
});
textPromises.push(promise);
}
const iframeTexts = await Promise.all(textPromises);
return iframeTexts.filter(text => text.length > 0);
}
// Listen for messages from background script (for popup controls)
chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
if (request.action === 'stopReading') {
stopSpeech();
sendResponse({ success: true });
}
});
// Handle reading from cursor to end with iframe support
async function handleReadFromCursorToEnd(startElement) {
try {
// Get text using the new document-order approach
const textWithIframes = await getTextFromPositionToEndAsync(startElement);
if (textWithIframes && textWithIframes.length > 0) {
// Check if we have multiple text parts (indicating iframes)
const textParts = textWithIframes.split(/\[IFRAME_BREAK\]/);
if (textParts.length > 1) {
// Multiple parts - use queued reading
const filteredParts = textParts.filter(part => part.trim().length > 0);
queueTextForReading(filteredParts);
} else {
// Single part - speak directly
speakText(textWithIframes, true); // Mark as long read
}
return { success: true, text: textWithIframes.substring(0, 100) + '...' };
} else {
return { success: false, error: 'No text found' };
}
} catch (error) {
return { success: false, error: error.message };
}
}
// Enhanced version that handles cross-origin iframes
async function getTextFromPositionToEndAsync(startElement) {
if (!startElement) return '';
// Create a tree walker that includes both text nodes and iframe elements
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
{
acceptNode: function(node) {
// Accept iframe elements
if (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'IFRAME') {
return NodeFilter.FILTER_ACCEPT;
}
// Accept text nodes (but skip script and style)
if (node.nodeType === Node.TEXT_NODE) {
const parent = node.parentElement;
if (parent && (parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE')) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
}
}
);
let nodes = [];
let node;
// Collect all nodes in document order
while (node = walker.nextNode()) {
nodes.push(node);
}
// Find the starting position
let startIndex = -1;
for (let i = 0; i < nodes.length; i++) {
const currentNode = nodes[i];
if (currentNode.nodeType === Node.TEXT_NODE) {
if (currentNode.parentElement === startElement ||
startElement.contains(currentNode)) {
startIndex = i;
break;
}
}
}
// If we couldn't find the start position, try to find it by position
if (startIndex === -1) {
const startRect = startElement.getBoundingClientRect();
for (let i = 0; i < nodes.length; i++) {
const currentNode = nodes[i];
if (currentNode.nodeType === Node.TEXT_NODE) {
const range = document.createRange();
range.selectNode(currentNode);
const nodeRect = range.getBoundingClientRect();
if (nodeRect.top >= startRect.top && nodeRect.left >= startRect.left) {
startIndex = i;
break;
}
}
}
}
if (startIndex === -1) {
// Fallback to just the element's text
return getElementText(startElement);
}
// Process nodes from start position to end
const textParts = [];
const iframePromises = [];
for (let i = startIndex; i < nodes.length; i++) {
const currentNode = nodes[i];
if (currentNode.nodeType === Node.TEXT_NODE) {
const text = currentNode.textContent.trim();
if (text) {
textParts.push(text);
}
} else if (currentNode.nodeType === Node.ELEMENT_NODE && currentNode.tagName === 'IFRAME') {
// Mark iframe position
const iframeIndex = textParts.length;
textParts.push('[IFRAME_PLACEHOLDER]');
// Try to get iframe content
const iframePromise = getIframeTextAsync(currentNode, iframeIndex);
iframePromises.push(iframePromise);
}
}
// Wait for all iframe content
const iframeResults = await Promise.all(iframePromises);
// Replace placeholders with actual iframe content
for (const result of iframeResults) {
if (result.text) {
textParts[result.index] = result.text;
} else {
textParts[result.index] = ''; // Remove placeholder if no content
}
}
return textParts.filter(part => part.length > 0).join(' ').replace(/\s+/g, ' ').trim();
}
// Get iframe text with async support for cross-origin
async function getIframeTextAsync(iframe, index) {
try {
// Try same-origin first
const iframeText = getTextFromIframe(iframe);
if (iframeText) {
return { index, text: iframeText };
}
} catch (e) {
// Cross-origin iframe, try postMessage
}
// Try cross-origin approach
const frameId = `frame_${index}_${Date.now()}`;
return new Promise((resolve) => {
const timeout = setTimeout(() => {
resolve({ index, text: '' }); // Timeout after 2 seconds
}, 2000);
const messageHandler = (event) => {
if (event.data && event.data.action === 'iframeTextResponse' && event.data.frameId === frameId) {
clearTimeout(timeout);
window.removeEventListener('message', messageHandler);
resolve({ index, text: event.data.text || '' });
}
};
window.addEventListener('message', messageHandler);
try {
iframe.contentWindow.postMessage({
action: 'getIframeText',
frameId: frameId
}, '*');
} catch (e) {
clearTimeout(timeout);
window.removeEventListener('message', messageHandler);
resolve({ index, text: '' });
}
});
}
// Initialize the extension
if (initializeSpeech()) {
// Add event listeners
document.addEventListener('mousemove', handleMouseMove, true);
document.addEventListener('contextmenu', handleContextMenu, true);
// Add cross-frame message listener
window.addEventListener('message', handleFrameMessage, true);
// Add keyboard shortcut to stop reading (Escape key)
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && isReading) {
stopSpeech();
event.preventDefault();
}
});
console.log('Text Reader Extension loaded successfully in', isMainFrame ? 'main frame' : 'iframe');
} else {
console.error('Text Reader Extension failed to initialize');
}