-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
73 lines (68 loc) · 2.07 KB
/
background.js
File metadata and controls
73 lines (68 loc) · 2.07 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
// Function to create offscreen document if it doesn't exist
async function createOffscreen() {
if (await chrome.offscreen.hasDocument()) return;
await chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['AUDIO_PLAYBACK'],
justification: 'Playing audio'
});
}
// Create context menu
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "sendToTTSServer",
title: "Send to TTS Server",
contexts: ["selection"],
});
});
// Handle context menu click
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "sendToTTSServer" && info.selectionText) {
text_to_speech(info.selectionText, tab.id);
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "speak") {
text_to_speech(message.text, sender.tab.id);
}
});
function text_to_speech(text, tabId) {
// Get the saved URL
chrome.storage.sync.get("serverUrl", async (data) => {
const serverUrl = data.serverUrl;
if (!serverUrl) {
console.log(
"TTS Server URL is not set. Please set it in the extension popup.",
);
return;
}
await createOffscreen();
try {
// Send the selected text to the server
const response = await fetch(serverUrl, {
method: "POST",
headers: { "Content-Type": "text/plain" },
body: text,
});
if (!response.ok) {
console.log("Failed to send text. Check the server.");
throw new Error("Server error");
}
const audioBlob = await response.blob();
// Convert blob to base64
const reader = new FileReader();
reader.readAsDataURL(audioBlob);
reader.onloadend = function () {
const base64Audio = reader.result;
chrome.runtime.sendMessage({
action: "playAudio",
audioData: base64Audio,
});
console.log("Audio data sent to content script!");
};
} catch (error) {
console.log(`Error: ${error.message}`);
console.log(`Tried to fetch from: ${serverUrl}`);
}
});
}