-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery-pdf.js
40 lines (33 loc) · 1.34 KB
/
query-pdf.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
(async function () {
const selectedText = window.getSelection().toString().trim();
if (!selectedText) {
window.postMessage({ type: 'getSelectedTextReply', selectedText: '' }, '*');
return;
}
try {
// Locate the PDF.js viewer's text content layer
const textLayers = document.querySelectorAll('.textLayer div');
if (!textLayers.length) {
console.warn('No text layers found in the PDF viewer.');
window.postMessage({ type: 'getSelectedTextReply', selectedText }, '*');
return;
}
// Iterate through text layers to match the selected text
let extractedText = '';
for (const textLayer of textLayers) {
if (selectedText.includes(textLayer.textContent.trim())) {
extractedText += `${textLayer.textContent.trim()} `;
}
}
// Send the matched text back
window.postMessage(
{ type: 'getSelectedTextReply', selectedText: extractedText.trim() || selectedText },
'*'
);
} catch (error) {
console.error('Error extracting text from PDF:', error);
window.postMessage({ type: 'getSelectedTextReply', selectedText }, '*');
}
})();
// // Use the embedded plugin's postMessage API to retrieve the selected text
// document.querySelector('embed').postMessage({ type: 'getSelectedText' }, '*');