aboutsummaryrefslogtreecommitdiffstats
path: root/src/background/run-ocr.ts
blob: 4d0b080c1ebed35269822d7a843d7e41a7ffb270 (plain)
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
const OFFSCREEN_DOCUMENT_PATH = "offscreen/ocr/index.html";

// Function to ensure the offscreen document is open
/**
 * Ensures the offscreen OCR document is open.  If it already exists
 * this is a no-op.
 */
async function setupOffscreenDocument() {
	if (await chrome.offscreen.hasDocument()) {
		return; // Offscreen document already open
	}
	await chrome.offscreen.createDocument({
		url: OFFSCREEN_DOCUMENT_PATH,
		reasons: [chrome.offscreen.Reason.CLIPBOARD],
		justification: "Performing OCR with Tesseract.js in a long-running context."
	});
}

// Listen for messages from content scripts (and popup if applicable)
/**
 * Listens for `"OCR"` messages from content scripts.  Forwards the
 * image data URL to an offscreen document for Tesseract.js processing
 * and sends the recognised text back to the caller.
 */
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
	if (message.type === "OCR" && message.dataURL) {
		(async () => {
			try {
				// Ensure the offscreen document is open
				await setupOffscreenDocument();

				// Send the OCR request to the offscreen document
				const offscreenResponse = await chrome.runtime.sendMessage({
					type: "OFFSCREEN_OCR_REQUEST",
					dataURL: message.dataURL
				});

				if (offscreenResponse && offscreenResponse.success) {
					sendResponse(offscreenResponse);
				} else {
					sendResponse({ success: false, error: offscreenResponse?.error || "Unknown OCR error" });
				}
			} catch (error) {
				sendResponse({ success: false, error: (error as Error).message });
			}
		})();
		return true; // Indicate async response
	}

	return false;
});