-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
176 lines (150 loc) · 5.31 KB
/
background.js
File metadata and controls
176 lines (150 loc) · 5.31 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
/**
* Discord Message Translator - Background Script
* Author: Tomáš Mark
*
* Handles fetch requests from content script to bypass CORS restrictions
* Manages translator state and communicates with content scripts
*/
const logger = {
debug: (...args) => console.debug('[Discord Translator - Background]', ...args),
log: (...args) => console.log('[Discord Translator - Background]', ...args),
warn: (...args) => console.warn('[Discord Translator - Background]', ...args),
error: (...args) => console.error('[Discord Translator - Background]', ...args)
};
// Translator state
let translatorState = {
isActive: true, // Automatically active for Discord
stats: {
translated: 0,
cached: 0
}
};
/**
* Get current state
*/
function getState() {
return { ...translatorState };
}
/**
* Initialize translator state on startup
*/
async function initializeState() {
// Load state from storage, default to active for Discord
const stored = await chrome.storage.local.get('translatorActive');
translatorState.isActive = stored.translatorActive !== undefined ? stored.translatorActive : true;
await chrome.storage.local.set({ translatorActive: translatorState.isActive });
logger.log('🚀 Translator initialized:', translatorState.isActive ? 'ACTIVE' : 'INACTIVE');
}
/**
* Toggle translator on/off
*/
async function toggleTranslator() {
translatorState.isActive = !translatorState.isActive;
logger.log('🔄 Translator toggled:', translatorState.isActive ? 'ON' : 'OFF');
// Save state to storage
await chrome.storage.local.set({ translatorActive: translatorState.isActive });
// Notify all Discord tabs
const tabs = await chrome.tabs.query({ url: '*://*.discord.com/*' });
for (const tab of tabs) {
try {
await chrome.tabs.sendMessage(tab.id, JSON.stringify({
type: 'stateChanged',
args: [translatorState.isActive]
}));
} catch (error) {
// Tab might not have content script loaded yet
logger.debug('Could not notify tab', tab.id, error.message);
}
}
return getState();
}
/**
* Update stats from content script
*/
function updateStats(stats) {
translatorState.stats = { ...stats };
logger.debug('📊 Stats updated:', stats);
}
/**
* Load saved state on startup (deprecated, use initializeState instead)
*/
async function loadState() {
const result = await chrome.storage.local.get('translatorActive');
translatorState.isActive = result.translatorActive ?? true; // Default ON for automatic translation
logger.log('📂 Loaded state:', translatorState.isActive ? 'ON' : 'OFF');
}
/**
* Handle messages from content scripts
*/
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
logger.log('📨 Message received, type:', typeof message);
logger.log('📨 Message content (first 200 chars):', typeof message === 'string' ? message.substring(0, 200) : message);
(async () => {
try {
const { type, args } = JSON.parse(message);
logger.log('✅ Parsed message type:', type);
switch (type) {
case 'fetch': {
const [url, options] = args;
logger.log('🌐 Proxying fetch request to:', url.substring(0, 100) + '...');
const response = await fetch(url, options);
logger.log('📥 Fetch response status:', response.status, response.statusText);
const text = await response.text();
logger.log('📄 Fetch response text length:', text.length);
logger.log('📄 First 200 chars:', text.substring(0, 200));
sendResponse(JSON.stringify({
ok: response.ok,
status: response.status,
statusText: response.statusText,
url,
text
}));
break;
}
case 'getState': {
const state = getState();
sendResponse(JSON.stringify(state));
break;
}
case 'toggleTranslator': {
const state = await toggleTranslator();
sendResponse(JSON.stringify(state));
break;
}
case 'updateStats': {
const [stats] = args;
updateStats(stats);
sendResponse(JSON.stringify({ success: true }));
break;
}
default:
logger.warn('Unknown message type:', type);
sendResponse(null);
}
} catch (error) {
logger.error('❌ Error handling message:', error);
logger.error('❌ Error stack:', error.stack);
sendResponse(JSON.stringify({ error: error.message }));
}
})();
return true; // Keep message channel open for async response
});
/**
* Extension lifecycle events
*/
chrome.runtime.onInstalled.addListener(async (details) => {
if (details.reason === 'install') {
logger.log('Extension installed');
// Set default state to ON for automatic translation
await chrome.storage.local.set({ translatorActive: true });
} else if (details.reason === 'update') {
logger.log('Extension updated to version', chrome.runtime.getManifest().version);
}
// Initialize state after install/update
await initializeState();
});
// Initialize state on startup
initializeState().then(() => {
logger.log('Discord Message Translator v' + chrome.runtime.getManifest().version + ' - Background script initialized');
logger.log('Initial state:', translatorState.isActive ? 'ON (automatic)' : 'OFF');
});